Android 保存切换按钮和文本视图状态

Android 保存切换按钮和文本视图状态,android,android-togglebutton,Android,Android Togglebutton,我是安卓新手。我想在选中切换按钮时更改文本的颜色,然后保存切换按钮和文本颜色的状态,即使应用程序被关闭。谁能告诉我怎么做。谢谢。这里是切换按钮和带有首选项的文本视图(用于保存状态)的简单示例 以下面的方式创建布局文件 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_w

我是安卓新手。我想在选中切换按钮时更改文本的颜色,然后保存切换按钮和文本颜色的状态,即使应用程序被关闭。谁能告诉我怎么做。谢谢。

这里是切换按钮和带有首选项的文本视图(用于保存状态)的简单示例

以下面的方式创建布局文件

<?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>


希望能有帮助

这个问题太宽泛了。您尝试过什么?使用共享的prefs来存储状态,并在需要时从中重新获取状态!!
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));
        }
    }
}