开发者

How to pass a boolean field from one activity to a class?

开发者 https://www.devze.com 2023-04-10 00:04 出处:网络
How to pass, at any time!, a boolean fie开发者_开发百科ld from one activity to a class?Pass to Activity:

How to pass, at any time!, a boolean fie开发者_开发百科ld from one activity to a class?


Pass to Activity:

Intent i = new Intent(getBaseContext(), NameOfActivity.class);
i.putExtra("my_boolean_key", myBooleanVariable);
startActivity(i)

Retrieve in Second Activity:

Bundle bundle = getIntent().getExtras();
boolean myBooleanVariable = bundle.getBoolean("my_boolean_key");


You can create your own singleton class that both your Activity and other class can access at any time. You have to be careful with it because it does add a layer of global variables (which people tend to not like), but it works.

public class MyBoolean{

   private static final MyBoolean instance = new MyBoolean();

   private boolean boolValue = false;

   private MyBoolean(){}

   public static MyBoolean getInstance(){
      return instance;
   }

   public boolean getValue(){
      return boolValue;
   }

   public void setValue(boolean newValue){
      boolValue = newValue;
   }
}

Call MyBoolean.getInstance() and you can use the methods inside which will be in sync with your whole program.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号