保存按钮的背景?

我有一个有背景的切换按钮。我想在用户关闭应用程序或离开 MainActivity 时保存该背景状态。我设法保存切换布尔值的状态,但不保存切换本身的图像背景。有人有主意吗?请参阅下面我的代码以获取更多信息。


private ToggleButton mtoggle;


public static final String SHARED_PREFS = "sharedPrefs";

public static final String M_TOGGLE = "mtoggle";


private boolean SwitchON_OFF;

以下是我的保存、加载和更新方法。再次保存切换布尔值的状态是没有问题的。只是不知道从哪里开始保存切换按钮的背景状态(一旦按下,背景就会从灰色变为黄色,反之亦然)。需要保存它的每个状态。


public void saveData(){


    SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);

    SharedPreferences.Editor editor = sharedPreferences.edit();


    editor.putBoolean(M_TOGGLE,mtoggle.isChecked()); // saving toggle state no problem.



    editor.apply();


    Toast.makeText(this, "Saved", Toast.LENGTH_SHORT ).show();


}


public  void loadData(){

    SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);


    SwitchON_OFF = sharedPreferences.getBoolean(M_TOGGLE,false);


}


public void updateViews(){

    mtoggle.setChecked(SwitchON_OFF);

}


桃花长相依
浏览 44回答 1
1回答

倚天杖

你可以这样做:-根据您的要求,您可以使用 if 条件。可绘制文件:- 两种颜色:-第一:-<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"android:shape="rectangle"><stroke&nbsp; &nbsp; android:width="1dp"&nbsp; &nbsp; android:color="@color/sky_blue"&nbsp; &nbsp; android:drawable="@android:color/transparent" /><solid android:color="@color/message_fragment_button" /><corners&nbsp; &nbsp; android:bottomLeftRadius="@dimen/dp_10"&nbsp; &nbsp; android:bottomRightRadius="@dimen/dp_10"&nbsp; &nbsp; android:topLeftRadius="@dimen/dp_10"&nbsp; &nbsp; android:topRightRadius="@dimen/dp_10" /></shape>第二:-<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"android:shape="rectangle"><stroke&nbsp; &nbsp; android:width="1dp"&nbsp; &nbsp; android:color="@color/sky_blue"&nbsp; &nbsp; android:drawable="@android:color/transparent" /><solid android:color="@color/sky_blue" /><corners&nbsp; &nbsp; android:bottomLeftRadius="@dimen/dp_10"&nbsp; &nbsp; android:bottomRightRadius="@dimen/dp_10"&nbsp; &nbsp; android:topLeftRadius="@dimen/dp_10"&nbsp; &nbsp; android:topRightRadius="@dimen/dp_10" /></shape>在 Java 中:-if (MessageConfirmed.equals("Yes")) {&nbsp; &nbsp; &nbsp; &nbsp; btn_confirm.setText("Confirmed");&nbsp; &nbsp; &nbsp; &nbsp; btn_confirm.setBackground(ContextCompat.getDrawable(context,&nbsp;R.drawable.confirm_button_blue));&nbsp; &nbsp; &nbsp; &nbsp; btn_confirm.setEnabled(false);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; btn_confirm.setText("Confirm");&nbsp; &nbsp; &nbsp; &nbsp; btn_confirm.setBackground(ContextCompat.getDrawable(context,&nbsp;R.drawable.confirm_button_green));&nbsp; &nbsp; &nbsp; &nbsp; btn_confirm.setEnabled(true);}但是,您需要在 XML 文件中定义最初的背景颜色。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java