2

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

我的适配器:

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

    });
    }
}
4

3 回答 3

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();
            }
        });
于 2012-04-23T18:36:15.690 回答
1

要保存选择,请创建一个方法 saveSelections 并在onPause()and中调用它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();
于 2012-04-23T17:54:56.550 回答
0

您可以创建一个 0 和 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;

现在存储这个字符串。再次开始活动时,使用此字符串设置复选框。

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

于 2012-04-23T18:12:14.283 回答