我是android的新手。我想在选中切换按钮时更改文本的颜色,然后保存切换按钮和文本颜色的状态,即使应用程序被终止也是如此。有人可以给我一些如何做到这一点的提示。感谢。
答案 0 :(得分:0)
这里是切换按钮和带有首选项的文本视图的简单示例(用于保存状态)。
以下方式创建布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dip"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New ToggleButton" />
</LinearLayout>
在您的活动中
public class MainActivity extends AppCompatActivity {
TextView textItem;
SharedPreferences sPref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
// init Preferences
sPref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
// init view
textItem = (TextView) findViewById(R.id.textView);
ToggleButton syncSwitch = (ToggleButton) findViewById(R.id.toggleButton1);
// toggle button event
syncSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set text color method
setTextColor(isChecked);
// save Toggle button state in Preference
SharedPreferences.Editor ed = sPref.edit();
ed.putBoolean("ToggleButton_CHECK", isChecked);
ed.commit();
}
});
// set default color if TextView called when activity started only for first time
boolean saveState = sPref.getBoolean("ToggleButton_CHECK", false);
setTextColor(saveState);
syncSwitch.setChecked(saveState);
}
public void setTextColor(boolean isChecked) {
if (isChecked) {
// button is on
textItem.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.agro_purple));
} else {
// button is off
textItem.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.colorAccent));
}
}
}
希望有所帮助!