我决定使用sharedPreferences,因此我可以在我的活动首选项中存储togglebutton的值。在我的主要活动中,当用户单击“首选项”活动中的“推特”按钮时,我想隐藏一个推特按钮。
private SharedPreferences prefs;
private String prefName = "MyPref";
private ToggleButton timer, twitter;
// this is the key used to set the timer to visible or hidden
private static final String TIMER_KEY = "timekey";
private static final String TWITTER_KEY= "tweet";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preferences);
timer = (ToggleButton)findViewById(R.id.timer_pref);
twitter =(ToggleButton)findViewById(R.id.twitter_pref);
timer.setChecked(true);
twitter.setChecked(true);
// Toast.makeText(Preferences.this, timer, Toast.LENGTH_SHORT).show();
Button b = (Button) findViewById(R.id.home_btn);
b.setOnClickListener(new View.OnClickListener()
{
// now add the new screen
public void onClick(View arg0) {
// TODO Auto-generated method stub
// get the shared perference data
Intent i = new Intent(Preferences.this, AndroidGUIActivity.class);
startActivity(i);
}
});
twitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
prefs = getSharedPreferences("MyPref", 0 );
SharedPreferences.Editor editor = prefs.edit();
if (timer.isChecked() == true)
{
editor.putBoolean("twitterButtonStatus", true);
}
else if(timer.isChecked() == false)
{
editor.putBoolean("twitterButtonStatus", false);
}
// now save the value that is passed to the editor.putBoolean function
// the twitter data hase been saved
editor.commit();
// now store the variable so that it can be copied to another activity
Bundle b = new Bundle();
}
});
答案 0 :(得分:1)
无需使用意图通过活动转移首选项。
您可以从任何活动访问“共享”偏好设置。
您只需将按钮状态设置为字符串键:
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("twitterButtonStatus", buttonStatus);
在另一个活动中,您使用字符串键(“twitterButtonStatus”)检索这些首选项:
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
boolean buttonStatus = settings.getBoolean("twitterButtonStatus", false); // second param is default!
请参阅:http://developer.android.com/guide/topics/data/data-storage.html
编辑:
你现在正在保存SharedPrefs,让他们回来并设置你的Button Gone做这样的事情:
SharedPreferences settings = getSharedPreferences(prefName, 0);
boolean buttonStatus = settings.getBoolean(TWITTER_KEY, true); //2nd is default
if(buttonstatus==false) twitter.setVisibility(View.GONE);