使用数组适配器保存listview simple_list_item_multiple_choice复选框状态

时间:2012-08-05 10:54:30

标签: android listview checkbox

我是Android设备编程新手。我试图弄清楚如何保存使用simple_list_item_multiple_choice和Array Adapter生成的listview中的复选框。我希望能够保存复选框的状态,以便当用户点击后退按钮转到另一个清单时,他们可以返回到此清单并从他们离开的地方取货。

拜托,请帮助!!代码和/或解释是理想的。

代码:

public class BeachBabyStuff extends Activity  {
    String[] beachstuffbaby = new String[]{                                                                
                        "Beach Blanket or Mat",                                             
            "Beach Towels",                                                                      
            "Beach Umbrella",                                                                  
            "Beach Chair",                                                                        
            "Books / Magazines",                                                              
            "Radio",                                                                      
            "Pen / Paper",                                                              
            "Tablet"};                                                                    


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview);


        // Getting the reference to the listview object of the layout
        ListView listView = (ListView) findViewById(R.id.listview);

        // The checkbox for the each item is specified by the layout android.R.layout.simple_list_item_multiple_choice
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, beachstuffbaby);


        // Setting adapter to the listview
        listView.setAdapter(adapter);

        //Manage the onItemClick method
        listView.setOnItemClickListener(new OnItemClickListener() {

            private View view;

            public void onItemClick(AdapterView<?> ListView, View view, int position, long id) {
                         CheckedTextView textView = (CheckedTextView)view;
                         textView.setChecked(!textView.isChecked());

                         this.view = view;

                                    }

        });

1 个答案:

答案 0 :(得分:0)

为维护检查的activty添加一个布尔数组。

boolean checked[] = new boolean[beachstuffbaby.length];

将所有选中的位置设置为此数组。从此数组中创建逗号分隔的项字符串,并将其放入SharedPreferences

通过从首选项中读取此数组并在逗号上拆分字符串来恢复状态。