android - 开关按钮始终打开

标签 android

首先,我对这个 android 编程还很陌生。我想问一下,为什么当我启动我的应用程序时我的开关总是打开。当我将其关闭并转到另一个 Activity 并返回到第一个 Activity 时,开关按钮再次打开 任何线索? 我试过 Android ToggleButton always check但我还是不明白。

    switchStatus = (TextView) findViewById(R.id.View1);
    mySwitch.setChecked(true);
    mySwitch = (Switch) findViewById(R.id.switch1);  

    mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

     @Override
     public void onCheckedChanged(CompoundButton buttonView,
     boolean isChecked) {

      if(mySwitch.isChecked()){
        mySwitch.setChecked(true);
        switchStatus.setText("Switch is currently On");
        onResume();          
        sendButton.setOnClickListener(new OnClickListener() {   
        @Override
        public void onClick(View arg0) {
        }
        });        
      }
      else{
       mySwitch.setChecked(false);
       switchStatus.setText("Switch is currently OFF");
       onPause();
      }
      }
      });

最佳答案

开关状态丢失,因为离开时Activity被销毁。所以你应该考虑保存 mySwitch 的状态。您可以使用 SharedPreferences 来完成此操作,或者...

you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting. Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.

关于android - 开关按钮始终打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27814980/

相关文章:

c# - 不接受 ItemEventArgs 或 ItemClickEventArgs 作为参数

android - 全局引用 R 的问题

android - 丰富的推送通知在展开包含图像的通知时不会隐藏大图标

android - 如何通过 Retrofit 在 @Query 中传递自定义枚举?

android - 为什么在我第一次打开 tabhost 的选项卡时调用 onResume?

android - flutter gradle异常退出(firebase认证)

android - 获取对父 ViewGroup 的引用

java - 将字符串转换为整数不起作用,抛出 NumberFormatException

java - Firebase RecyclerView 显示一项

java - Android - 强制关闭、PDF 不可用、iText