Android global variable

前端 未结 14 1083
眼角桃花
眼角桃花 2020-11-21 23:32

How can I create global variable keep remain values around the life cycle of the application regardless which activity running.

14条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 23:57

    You can create a Global Class like this:

    public class GlobalClass extends Application{
    
        private String name;
        private String email;
    
        public String getName() {
            return name;
        }
    
        public void setName(String aName) {
            name = aName;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String aEmail) {
            email = aEmail;
        }
    }
    

    Then define it in the manifest:

    Now you can set values to global variable like this:

    final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
    globalVariable.setName("Android Example context variable");
    

    You can get those values like this:

    final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
    final String name  = globalVariable.getName();
    

    Please find complete example from this blog Global Variables

提交回复
热议问题