Save state of Button in activity Android

房东的猫 提交于 2019-12-25 09:42:23

问题


I have two buttons(button1, button2) in my activty. botton1 is 'Enabled'(true) , while the other one isn't.

When I click on button1, button2 becomes 'Enabled'. I want to record this activity in this state for the next utilization of my application.


回答1:


You can save state in sharedPrefrences, try this

SharedPreferences prefs = getSharedPreferences("Your preference name here", MODE_PRIVATE) 


b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                b2.setEnabled(true);
                prefs.edit().putBoolean("b2enabled", true).commit();//saving State here
            }
        });

And now where you want to use this state simple get the state as.

Boolean b2state= prefs.getBoolean("b2enabled", false); //false is the default value

And if you want to enable or disable button on result do

if (b2state){
b2.enabled(true);
}
else{
b2.enabled(false);
}



回答2:


Well, you can use the help of a data storage option. For a simple task like this, shared preference is enough. use something like this to store the state change.

function setState(boolean state){
    SharedPreferences sharedPref =this.getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putBoolean("state",state);
}

you can retrieve the data at anytime (usually in in the beginning) like this. Note that the second argument serves the default value.

int state=this.getPreferences(Context.MODE_PRIVATE).getBoolean("state",false);

Hope this helps.



来源:https://stackoverflow.com/questions/44099496/save-state-of-button-in-activity-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!