为什么setChecked on Switch不起作用?

时间:2014-11-11 05:33:40

标签: android

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

switch.setChecked(isChecked);

isChecked来自savedInstanceState。但问题是setChecked(true)无效。

MainActivity.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>

2 个答案:

答案 0 :(得分:0)

问题是你的价值是&#34;切换&#34;密钥总是错误的。您只需在此处输入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();    
    }
});

答案 1 :(得分:0)

你有没有解决这个问题?在过去的三天里,我遇到了同样的问题。我现在已经解决了这个问题。如果您的setChecked(true)无法显示用户定义的开关,也许您可​​以在自定义<中添加 width height 属性em> switch track_on.xml。这个解决方案正在解决我的问题。愿它可以帮到你。