[英]Custom Toggle button with share preferences
I am trying to setup a custom toggle button where I use an Imagebutton and two different images to show which state is toggled. 我试图设置一个自定义切换按钮,在此我使用一个Imagebutton和两个不同的图像来显示哪个状态被切换。 Right now I can toggle the picture listening for a click:
现在,我可以切换图片以聆听点击:
togglebtn = (ImageButton) findViewById(R.id.togglebtn);
togglebtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
togglebtn.setImageResource(R.drawable.offbtn);
}
});
But I am not sure how to use sharepreferences save the state that the user selects. 但是我不确定如何使用共享首选项保存用户选择的状态。 I want to use a boolean but all the shareprefences examples I find with booleans are all specific to check box not something like this.
我想使用布尔值,但是我在布尔值中找到的所有shareprefences示例都是特定于复选框的,而不是这样的。
How can I save the state of my toggle button? 如何保存切换按钮的状态?
try something like that (coded out of the head) 尝试类似的东西(从头顶编码)
editor = sharedPreferences.edit();
boolean b = true;
editor.putBool("myBoolean", b);
editor.commit();
I would recommend you to save that onPause() of your activity and not onClick since I think it is expensive. 我建议您保存活动的onPause()而不保存onClick,因为我认为这很昂贵。
further from @Anthea comment regarding the preferences, you shouldn't be using the ImageButton. 除了@Anthea关于首选项的注释之外,您不应该使用ImageButton。
There are ToggleButton, CheckBox and Switch for boolean options implementation. 有用于布尔选项实现的ToggleButton,CheckBox和Switch。 You should check them.
您应该检查它们。 You also shouldn't be programmatically changing the drawable.
您也不应该以编程方式更改可绘制对象。 You can/should set a selector drawable XML with the pressed and not pressed and set them on the layout.
您可以/应该通过按和不按选择器来设置选择器可绘制的XML,并在布局上进行设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.