使用sharedpreferences保存复选框状态

时间:2014-08-18 19:39:59

标签: android listview

在我的代码中,我添加了共享偏好,但除了它之外没有任何保存。我需要的是,当用户勾选几个复选框时,当重新启动应用程序或按下后退按钮时,复选框应该仍然相同。

这是我的代码:

public class MyActivity3 extends Activity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my3);
    Button m = (Button) findViewById(R.id.button3);
    tv = (TextView) findViewById(R.id.textViewcat);
    Typeface typeface = Typeface.createFromAsset(getAssets(), "BebasNeue Bold.ttf");
    tv.setTypeface(typeface);

        SharedPreferences sharedPreferences=getSharedPreferences("ticks", Context.MODE_PRIVATE);
    sharedPreferences.getString("name","");

    //LISTVIEW IS BELOW! Still needs check checkbox onItemClick and save state on exit and back pressed!
    String listArray[] = new String[] { "All", "Friends & Family", "Sports", "Outside",
            "At School", "Fitness", "Photography", "Food", "Beach", "Money" };
    ListView listView = (ListView) findViewById(R.id.listView);
    List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
    for (int i = 0; i <= listArray.length - 1; i++) {
       HashMap<String, String> hm = new HashMap<String, String>();
        hm.put("title", listArray[i]);
        aList.add(hm);
    }
    String[] sfrm = { "title"};
    int[] sto = { R.id.title};
    SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList,
            R.layout.row_layout, sfrm, sto);
   listView.setAdapter(adapter);
   listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

       @Override
       public void onItemClick(AdapterView<?> arg0, View view,
                               int position, long id) {
           switch (position) {
           }
       }
   });
}

public void save(View view)
{
        SharedPreferences sharedPreferences=getSharedPreferences("ticks", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor=sharedPreferences.edit();
    editor.putString("key","");
    editor.commit();
}
@Override
public void onBackPressed() {
    super.onBackPressed();
    overridePendingTransition(R.anim.animation8, R.anim.animation7);
    }
}

这里是我的.xml,其中复选框有一个onClick =&#34; save&#34; :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >

<com.MR.brd.CustomTextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:text="Country name"
    android:textColor="#FFFFFF"
    android:textSize="48sp" />

<CheckBox android:id="@+id/chk"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@drawable/custom_checkbox_design"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:onClick="save"/>


</RelativeLayout>

我做错了吗?我遵循共享偏好的教程,但显然我没有得到它...

2 个答案:

答案 0 :(得分:1)

您没有在共享偏好设置中保存任何内容:

editor.putString("key","");

始终保存空字符串。在onCreate上,您没有使用检索到的字符串,您必须使用相同的密钥。

sharedPreferences.getString("name","");

您必须更改&#34; 名称&#34;对于&#34; &#34;。

在CheckBox上检查状态更改时,您也没有捕获事件。在代码的某些部分中,必须为复选框设置OnCheckedChangeListener,因为在选择一个ListView视图时会触发setOnItemClickListener,而不是在选中或取消选中复选框时触发。

修改onCreate Activity方法,然后删除保存方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my3);
    Button m = (Button) findViewById(R.id.button3);
    tv = (TextView) findViewById(R.id.textViewcat);
    Typeface typeface = Typeface.createFromAsset(getAssets(), "BebasNeue Bold.ttf");
    tv.setTypeface(typeface);

    String[] listArray = new String[] { "All", "Friends & Family", "Sports", "Outside", "At School", "Fitness", "Photography", "Food", "Beach", "Money" };
    SharedPreferences sharedPreferences = getSharedPreferences("status", MODE_PRIVATE);

    Boolean[] checkedStatus = new Boolean[listArray.length];
    for ( int index = 0; index < checkedStatus.length; index++)
        checkedStatus[index] = sharedPreferences.getBoolean(Integer.toString(index), false);

    ListView listView = (ListView) findViewById(R.id.listview);
    MyAdapter adapter = new MyAdapter(this, R.layout.row_layout, listArray, checkedStatus);
    listView.setAdapter(adapter);
}

创建MyAdapter类:

public class MyAdapter extends ArrayAdapter<String> implements CompoundButton.OnCheckedChangeListener{

String[] values;
Boolean[] checkedStatus;

public MyAdapter(Context context, int resource, String[] values, Boolean[] checkedStatus) {
    super(context, resource, values);

    this.values = values;
    this.checkedStatus = checkedStatus;
}

@Override
public int getCount() {
    return values.length;
}

@Override
public String getItem(int position) {
    return values[position];
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if(view == null){
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.row_layout, null);
    }

    TextView textView = (TextView) view.findViewById(R.id.title);
    textView.setText(values[position]);

    CheckBox box = (CheckBox) view.findViewById(R.id.chk);
    box.setTag(position);
    box.setOnCheckedChangeListener(this);
    box.setChecked(checkedStatus[position]);

    return view;
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    Integer index = (Integer) buttonView.getTag();
    checkedStatus[index] = isChecked;
    String key = index.toString();

    SharedPreferences sharedPreferences=getContext().getSharedPreferences("status", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor=sharedPreferences.edit();
    editor.putBoolean(key,isChecked);
    editor.apply();
}

}

另外,修改.xml文件的复选框声明:

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:text="Country name"
    android:textColor="#FFFFFF"
    android:textSize="48sp" />

<CheckBox android:id="@+id/chk"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@drawable/custom_checkbox_design"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"/>

去除,

android:onClick="save"

答案 1 :(得分:0)

如果您想保存大量代码(以及可能的错误),您可以使用AXT - 那么它看起来像这样:

AXT.at(yourCheckBox).careForCheckedStatePersistence("some_tag");

您的案例中的代码需要您的复选框的位置。

https://github.com/ligi/AXT