簡體   English   中英

使用共享首選項保存復選框狀態

[英]Save checkbox state with sharedpreferences

在我的代碼中,我添加了sharedpreferences等所有內容,但它並沒有保存任何內容。 我需要的是,當用戶勾選幾個復選框時,重新啟動應用程序或按下“后退”按鈕時,這些復選框仍應相同。

這是我的代碼:

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 =“ save”:

<?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>

難道我做錯了什么? 我遵循了有關sharedpreferences的教程,但是顯然我沒有以某種方式得到它...

您不會在共享首選項上保存任何內容:

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

始終保存一個空字符串。 在onCreate上,您不使用檢索到的字符串,並且必須使用相同的鍵。

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

您必須將“ ”更改為“ 名稱 ”。

同樣,在CheckBox上檢查狀態更改時,您也不會捕獲事件。 在代碼的某些部分中,必須為復選框設置OnCheckedChangeListener,因為在選擇ListView的一個視圖時(而不是在選中或取消選中CheckBox時)會觸發setOnItemClickListener。

修改您的onCreate Activity方法,並刪除save方法:

@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"

如果您想保存很多代碼(以及可能的錯誤),則可以使用AXT-如下所示:

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

您的案例中的標簽需要您的復選框的位置。

https://github.com/ligi/AXT

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM