为什么开关上的setChecked不起作用



我正在onSaveInstanceState中保存开关切换的状态,并在onRestoreInstanceState中检索它。每当我旋转屏幕时,我都想恢复开关的状态。如果我将开关设置为ON,它将保存为true,但在旋转屏幕上,活动将被重新创建,所以我使用

switch.setChecked(isChecked);

isChecked来自savedInstanceState。但问题是setChecked(true)不起作用。

主要活动.java

package com.chinmay.callblocker;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private Switch mSwitch;
private AudioManager mAudio;
private TextView extraTxt;
CustomListAdapter adapter;
String[] itemname ={
        "Activate",
        "Message",
        "Global",
        "FireFox",
        "UC Browser",
        "Android Folder"
};
Integer[] imgid={
        R.drawable.pic1,
        R.drawable.message,
        R.drawable.pic3,
        R.drawable.pic4,
        R.drawable.pic5,
        R.drawable.pic6
};
String[] textDescription = {
        "Turn on to  block calls",
        "Set a custom message",
        "Description Global",
        "Description FireFox",
        "Description UC Browser",
        "Description Android Folder"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    adapter = new CustomListAdapter(this, itemname, imgid, textDescription);
    setListAdapter(adapter);
    mAudio = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
    View inflatedView = getLayoutInflater().inflate(R.layout.mylist, null);
    mSwitch = (Switch) inflatedView.findViewById(R.id.switch1);

    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    final SharedPreferences.Editor e = settings.edit();
    e.putBoolean("switch", false);
    e.commit();
    getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, final int position, long l) {
            if(position == 1) {
                alert.setTitle("Message");
                alert.setMessage("This message will be sent when call blocking is on");
                // Set an EditText view to get user input
                final EditText input = new EditText(getBaseContext());
                input.setText(textDescription[position]);
                alert.setView(input);
                alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String value = input.getText().toString();
                        textDescription[1] = value;
                        adapter.notifyDataSetChanged();
                    }
                });
                alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // Canceled.
                    }
                });
                alert.show();
            }
        }
    });
}
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putString("current_message", textDescription[1]);
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    boolean isChecked = settings.getBoolean("switch", false);
    //Toast.makeText(this, "Current state of switch is "+ isChecked, Toast.LENGTH_SHORT).show();
    savedInstanceState.putBoolean("switchChecked", isChecked);
    super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    textDescription[1] = savedInstanceState.getString("current_message");
    adapter.notifyDataSetChanged();
    boolean switchChecked = savedInstanceState.getBoolean("switchChecked");
    //Toast.makeText(this, "Current state of switch is "+ switchChecked, Toast.LENGTH_SHORT).show();
    mSwitch.setChecked(switchChecked);
}
public void onListItemClick(ListView lv ,View view,int position,int imgid) {
    /*String selected_item = "List View";
    Toast.makeText(this, selected_item, Toast.LENGTH_SHORT).show();*/
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    //noinspection SimplifiableIfStatement
    if (id == R.id.action_logs) {
        return true;
    } else if(id == R.id.action_help) {
        return true;
    } else if(id == R.id.action_about) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

mylist.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal">
<ImageView
    android:id="@+id/icon"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:padding="5dp" />
<LinearLayout android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <LinearLayout android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:id="@+id/item"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Medium Text"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:padding="2dp"
            android:textColor="#33CC33" />
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView"
            android:layout_marginLeft="10dp"/>
     </LinearLayout>
    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1" />
    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="21dp"
        android:layout_marginBottom="21dp" />
</LinearLayout>

问题是"switch"键的值总是false。您只在此处输入false值:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor e = settings.edit();
e.putBoolean("switch", false);
e.commit();

然后永远不要改变这个值,所以SharedPreferences总是存储false的值。通过id找到交换机后,您需要将setOnCheckedChangeListener发送到交换机,如下所示:

mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
        final SharedPreferences.Editor e = settings.edit();
        e.putBoolean("switch", isChecked);
        e.commit();    
    }
});

您解决了这个问题吗?在过去的三天里,我遇到了同样的问题。我现在已经打消了这个问题。如果您的setChecked(true)无法为用户定义的开关显示,也许您可以在自定义交换机track_on.xml中添加宽度高度属性。此解决方案适用于我的问题。愿它能帮助你。

最新更新