android - 使用 SharedPreferences 在 ListView 中存储复选框的状态

标签 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;
    }

}

我的主要 Activity :

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

    });
    }
}

最佳答案

ButtonOnCLickListener 中添加以下内容:

//...
// 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;
}

最后在 dialogBu​​tton 的监听器中添加以下内容:

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

关于android - 使用 SharedPreferences 在 ListView 中存储复选框的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10285230/

相关文章:

android - 从 Preferences ListFragment 中以编程方式创建的 PreferenceScreen 中删除填充

android - 如何为 textview 从左到右 android 应用颜色过渡?

Android Studio 在短时间后自动关闭

android - 共享首选项和 boolean 值

android - 如何用大约 10 个变量在 Android 中保存项目?

java - iPhone、iPad 和 Windows Phone 应用程序部署为什么?

android - 如何正确处理嵌套 fragment ?

android - SharedPreferences 保存数据多长时间?

android - 检查用户是否登录

java - 静态 Linkedhashmap 还是 Sharedpreference?