0

我是安卓新手。我想在选中切换按钮时更改文本的颜色,然后即使在应用程序被终止时也保存切换按钮和文本颜色的状态。有人可以给我一些如何做到这一点的提示。谢谢。

4

1 回答 1

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));
        }
    }
}

希望对您有所帮助!

于 2016-02-04T05:39:11.167 回答