Android 使用SharedReferences保存复选框状态

Android 使用SharedReferences保存复选框状态,android,listview,Android,Listview,在我的代码中,我添加了SharedReference和所有内容,但它没有保存任何内容。我需要的是,当用户勾选几个复选框时,当应用程序重新启动或按下“后退”按钮时,复选框应该仍然相同 这是我的密码: public class MyActivity3 extends Activity { private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(save

在我的代码中,我添加了SharedReference和所有内容,但它没有保存任何内容。我需要的是,当用户勾选几个复选框时,当应用程序重新启动或按下“后退”按钮时,复选框应该仍然相同

这是我的密码:

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);
    }
}
公共类MyActivity3扩展活动{
私家图文电视;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my3);
按钮m=(按钮)findViewById(R.id.button3);
tv=(TextView)findViewById(R.id.textViewcat);
Typeface-Typeface=Typeface.createFromAsset(getAssets(),“BebasNeue Bold.ttf”);
设置字体(字体);
SharedReferences SharedReferences=GetSharedReferences(“ticks”,Context.MODE\u PRIVATE);
getString(“名称”,“参数”);
//LISTVIEW在下面!仍然需要选中复选框,单击并在退出时保存状态,然后按后退!
String listArray[]=新字符串[]{“全部”、“朋友和家人”、“运动”、“外部”,
“在学校”、“健身”、“摄影”、“美食”、“海滩”、“金钱”};
ListView ListView=(ListView)findViewById(R.id.ListView);
列表列表=新的ArrayList();

对于(int i=0;i您没有在共享首选项上保存任何内容:

editor.putString("key","");
始终保存空字符串。在onCreate上,您没有使用检索到的字符串,并且必须使用相同的键

sharedPreferences.getString("name","");
您必须将“键”更改为“名称”

此外,选中复选框状态更改时也无法捕获事件。在代码的某些部分中,必须为复选框设置OnCheckedChangeListener,因为setOnItemClickListener是在选中ListView的一个视图时触发的,而不是在选中或取消选中复选框时触发的

修改onCreate活动方法,并删除保存方法:

@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);
}

如果您想保存大量代码(以及可能的bug),可以使用AXT,它看起来如下所示:

AXT.at(yourCheckBox).careForCheckedStatePersistence("some_tag");
您案例中的标签需要复选框的位置


根据您的代码,当您按下复选框时,它会保存状态,但当您按下两个复选框时会发生什么情况?它会覆盖旧的复选框吗?您何时调用save函数?为什么用key保存而用name读取?我不确定,我想如果我将onClick放在.xml文件中就可以了,因为它对每个复选框都有效列表视图中的复选框。我确实必须更改名称。当按下一个复选框时,我会调用保存功能。如果您有多个复选框,则需要为每个复选框创建一个唯一的键。.plus String result=SharedReferences.getString(“名称”,“”);你忘了返回结果,你能帮我分享代码吗?我还是android编程新手:(所以只要把它改成key就可以了?或者我需要在空的“”标记之间放点什么吗?你能编辑我的代码让它工作吗?所有这些术语和东西,对新手来说都太多了:P*谢谢:)不,我将在我的答案上发布更改。好的,我将等待更改:)我是创建一个新的java类文件并在其中发布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();
}
<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"
AXT.at(yourCheckBox).careForCheckedStatePersistence("some_tag");