使用SharedPreferences在listview中存储checkbox的状态

时间:2012-04-23 17:24:53

标签: android sharedpreferences

如何在下次打开应用时使用共享偏好设置来存储我的复选框的状态?我正在使用自定义适配器,所以我猜它必须放在那里,但我不太确定。

我的适配器:

public class MobileArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();


    public MobileArrayAdapter(Context context, String[] values) {
        super(context, R.layout.list_adapter, values);
        this.context = context;
        this.values = values;


        for (int i = 0; i < this.getCount(); i++) {
            itemChecked.add(i, false);
        }
    }

    @Override
    public View getView(final int position, View convertView,
            ViewGroup parent) {
        View rowView = convertView;
        if (rowView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            rowView = inflater.inflate(R.layout.list_adapter,
                    parent, false);
        }
           // in your code you search for the CheckBox with the id checkBox1 2 times so I assumed that you are referring to the same view.
        CheckBox cBox = (CheckBox) rowView.findViewById(R.id.checkBox1);
        cBox.setTextColor(0xFFFFFFFF);
        cBox.setText(values[position]);       
        cBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                if (isChecked) {
                    itemChecked.set(position, true);
                    // do some operations here
                } else {
                    itemChecked.set(position, false);
                    // do some operations here
                }
            }
        });
        cBox.setChecked(itemChecked.get(position));
        return rowView;
    }

}

我的主要活动:

public class TheKevinAndEricaBoxActivity extends Activity {
/** Called when the activity is first created. */
private String[] myString;
private String list;
private String[] myString2;
private String list2;
private static final Random rgenerator = new Random();
private static final Random rgenerator2 = new Random();
MediaPlayer mp;
final Context mContext = this;
final Context context = this;
private Button button;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Resources res = getResources();
    addListenerOnButton();




    myString = res.getStringArray(R.array.myArray);

    list = myString[rgenerator.nextInt(myString.length)];

    myString2 = res.getStringArray(R.array.myArray2);

    list2 = myString2[rgenerator.nextInt(myString2.length)];
}



    public void addListenerOnButton() {

        final Context context2 = this;

        ImageButton ibg = (ImageButton) findViewById(R.id.buttongallery);

        ibg.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent intent = new Intent(context2, App2Activity.class);
                startActivityForResult(intent, 0);   

            }

        });


    ImageButton ib = (ImageButton) findViewById(R.id.imagebutton1);
    ib.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View erica) {
            AlertDialog.Builder b = new AlertDialog.Builder(
                    TheKevinAndEricaBoxActivity.this);
            b.setMessage(myString[rgenerator.nextInt(myString.length)]);
            b.setTitle(R.string.title1);
            b.setIcon(R.drawable.menuiconerica);
            b.setPositiveButton("Back",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            dialog.cancel();
                        }
                    });
            Dialog d = b.create();
            d.show();
        }
    });

    ImageButton ib2 = (ImageButton) findViewById(R.id.imagebutton2);
    ib2.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View kevin) {
            AlertDialog.Builder b = new AlertDialog.Builder(
                    TheKevinAndEricaBoxActivity.this);
            b.setMessage(myString2[rgenerator2.nextInt(myString2.length)]);
            b.setTitle(R.string.title2);
            b.setIcon(R.drawable.menuiconkevin);
            b.setPositiveButton("Back",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            dialog.cancel();
                        }
                    });
            Dialog d = b.create();
            d.show();

        }
    });


    ImageButton Ib3 = (ImageButton) findViewById(R.id.imagebutton3);
    Ib3.setOnClickListener(new View.OnClickListener() {
        public void onClick(View lemonclick) {
            mp = MediaPlayer.create(getApplicationContext(),R.raw.lemonspeech);
            mp.start();


        }
    });
    button = (Button) findViewById(R.id.button01);

    // add button listener
    button.setOnClickListener(new OnClickListener() {

      public void onClick(View arg0) {

        // custom dialog
        final Dialog dialog = new Dialog(context);
        dialog.setContentView(R.layout.list);
        dialog.setTitle("The List");


        // set the custom dialog components - text, image and button
        //TextView text = (TextView) dialog.findViewById(R.id.TextView01);
        //text.setText("Did you not read the button? :P i'm not finshed on this yet XD");


        ListView listView = (ListView) findViewById(R.id.myList);
        String[] values = new String[] { "value1", "value2", };


        MobileArrayAdapter mAdapter = new MobileArrayAdapter(getBaseContext(), values);
        ListView mListView = (ListView) dialog.findViewById(R.id.myList);
        mListView.setAdapter(mAdapter);


        Button dialogButton = (Button) dialog.findViewById(R.id.Button01);
        // if button is clicked, close the custom dialog
        dialogButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();
      }

    });
    }
}

3 个答案:

答案 0 :(得分:4)

OnCLickListener Button添加此内容:

//...
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.list);
dialog.setTitle("The List");

prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefsEditor = prefs.edit();
String currentlyStored = prefs.getString("checked_list", null);
int[] savedStatus = null;
if (currentlyStored != null) {
    String[] tmp = currentlyStored.split(",");
    savedStatus = new int[tmp.length];
    for (int i = 0; i < tmp.length; i++) {
        savedStatus[i] = Integer.parseInt(tmp[i]);
    }
}
adapter = new MobileArrayAdapter(this, soundnames, savedStatus);
ListView mListView = (ListView) dialog.findViewById(R.id.myList);
mListView.setAdapter(mAdapter);
//...

其中:

private SharedPreferences prefs;
private SharedPreferences.Editor prefsEditor;
private MobileArrayAdapter adapter;

您的班级中包含ListView的字段(adapter字段将保存您在列表中设置的适配器对象。)

修改自定义适配器的构造函数,如下所示:

public MobileArrayAdapter(Context context, String[] values,
                int[] oldStatus) {
            super(context, R.layout.adapters_simpleplay_row, values);
            this.context = context;
            this.values = values;

            // make every CheckBox unchecked and then loop through oldStatus(if
            // not null)
            for (int i = 0; i < this.getCount(); i++) {
                itemChecked.add(i, false);
            }
            if (oldStatus != null) {
                for (int j = 0; j < oldStatus.length; j++) {
                    itemChecked.set(oldStatus[j], true);
                }
            }
        }

还在自定义适配器MobileArrayAdapter中添加以下方法:

public ArrayList<Boolean> getCheckedStatus() {
            return itemChecked;
}

最后在你的dialogButton的监听器中添加:

dialogButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                            String toStore = "";
            ArrayList<Boolean> status = adapter.getCheckedStatus();
            for (int i = 0; i < status.size(); i++) {
                if (status.get(i)) {
                    toStore += i + ",";
                }
            }
            prefsEditor.putString("checked_list", toStore.equals("") ? null
                    : toStore.substring(0, toStore.length() - 1));
            prefsEditor.commit();
                dialog.dismiss();
            }
        });

答案 1 :(得分:1)

要保存选择,请创建一个方法saveSelections并在onPause()onDestroy()中调用它,或创建一个Button来为您执行相同操作... 编辑:

由于您使用的是ListView,它是MultipleChoice,我想您可以在onCreate中执行此操作...

listView = (ListView) findViewById(R.id.list);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listView.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_multiple_choice,
                android.R.id.text1, names));

在onCreate()

之外创建这三个方法
private void LoadSelections() {
        SharedPreferences sp = getPreferences(MODE_PRIVATE);
        if (sp.contains(LOAD_LIST)) {
            String savedItems = sp.getString(LOAD_LIST, "");
            this.selectedItems.addAll(Arrays.asList(savedItems.split(",")));
            int count = this.listView.getAdapter().getCount();
            for (int i = 0; i < count; i++) {
                String currentItem = (String) listView.getAdapter().getItem(i);
                if (this.selectedItems.contains(currentItem)) {
                    this.listView.setItemChecked(i, true);
                }

            }
        }
    }

    public void SaveSelections() {
        SharedPreferences sp = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor prefEditor = sp.edit();
        String savedItems = getSavedItems();
        prefEditor.putString(LOAD_LIST, savedItems);
        prefEditor.commit();
    }

    private String getSavedItems() {
        String savedItems = "";
        int count = listView.getAdapter().getCount();
        for (int i = 0; i < count; i++) {
            if (listView.isItemChecked(i)) {
                if (savedItems.length() > 0) {
                    savedItems += "," + listView.getItemAtPosition(i);
                } else {
                    savedItems += listView.getItemAtPosition(i);
                }
            }
        }
        return savedItems;
    }

然后在onPause()中,执行以下操作:

@Override
protected void onPause() {
    SaveSelections();
    super.onPause();
}

然后终于在onCreate上调用了这个..

LoadSelections();

答案 2 :(得分:0)

你可以创建一个0&amp;的字符串1并使用共享首选项存储它。您使用的复选框(或视图数)的数量将是字符串的长度。你可以相应地保存它。

例如:

String s[]="0000000000";
for (i=0;i<s.length();i++)
if (checkboxAtLocation(i)==true)    //checkboxAtLocation() will return a boolean variable on basis of its checked or not
    s[i]=1;

现在存储此字符串。 再次启动活动时,请使用此字符串设置复选框。

这实现起来有点复杂,但据我所知,这是最有效的方式。 我希望它能解决你的疑问。