开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜