不太了解开关问题,但您可以使用ToggleButton
如下:
在布局中定义按钮:
<ToggleButton
android:id="@+id/your_awesome_toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:gravity="center_vertical|center_horizontal"
android:layout_marginRight="15dp"
android:textOn=""
android:textOff=""
android:background="@drawable/toggle_button"
/>
创建一个选择器:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:state_checked="false"
android:state_focused="false"
android:drawable="@drawable/switch_off_btn" />
<item
android:state_checked="true"
android:state_focused="false"
android:drawable="@drawable/switch_on_btn" />
<item
android:drawable="@drawable/switch_off_btn" />
</selector>
OnClickListener
:
toggleOnOff = (ToggleButton) findViewById(R.id.your_awesome_toggle);
toggleOnOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateButtons();
if(toggleOnOff.isChecked()){
SharedPreferences emailPrefs = getSharedPreferences(rememberToggleOnOff,MODE_PRIVATE);
SharedPreferences.Editor editor = yourPrefs.edit();
editor.putBoolean("mon", true);
editor.commit();
}
else {
SharedPreferences emailPrefs = getSharedPreferences(rememberToggleOnOff,MODE_PRIVATE);
SharedPreferences.Editor editor = yourPrefs.edit();
editor.putBoolean("mon", false);
editor.commit();
}
}
});
checkToggleState();
checkToggleState
方法:
/**
* Checks the state of the Toggle button preferences.
* If preferences are true set the toggle to on, if false set the toggle off.
*
*/
private void checkToggleState() {
SharedPreferences yourPrefs = getSharedPreferences(rememberToggleOnOff,MODE_PRIVATE);
boolean mON = yourPrefs.getBoolean("mon", true);
if(mON) {
toggleOnOff.setChecked(true);
}
else {
toggleOnOff.setChecked(false);
}
}