在ListView存储复选框状态(Storing CheckBox state in a ListV

2019-07-29 02:36发布

我试图执行一段代码,我发现存储的状态CheckBox是在一个ListView ,但它并没有奏效。 有没有人有,为什么从我的适配器我的代码是不工作的任何想法?

package kevin.erica.box;

import java.util.ArrayList;

import kevin.erica.box.R;

import android.R.color;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

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); // initializes all items value with false
        }
    }


    @Override
    public View getView(final int position, View covertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View rowView = inflater.inflate(R.layout.list_adapter, parent, false);
            CheckBox textView = (CheckBox) rowView.findViewById(R.id.checkBox1);
            textView.setTextColor(0xFFFFFFFF);
            textView.setText(values[position]);
            //Store state attempt
            final CheckBox cBox = (CheckBox) rowView.findViewById(R.id.checkBox1); // your
            // CheckBox
            cBox.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {

                CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox1);

                if (cb.isChecked()) {
                    itemChecked.set(position, true);
                    // do some operations here
                } else if (!cb.isChecked()) {
                    itemChecked.set(position, false);
                    // do some operations here
                }
            }
        });
        cBox.setChecked(itemChecked.get(position)); // this will Check or Uncheck the
        // CheckBox in ListView
        // according to their original
        // position and CheckBox never
        // loss his State when you
        // Scroll the List Items.
        return rowView;
    }
}

Answer 1:

你的问题没有说关于存储数据的应用程序关闭后什么。 要保存检查CheckBoxes ,你可以使用一个数据库或一个简单的文件。 波纹管是存储的一个例子CheckBox在数据库状态:

public class SimplePlay extends ListActivity {

    private String[] soundnames;
    private Helper mHelper = new Helper(this, "position_status.db", null, 1);
    private SQLiteDatabase statusDb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // this is to simulate data
        soundnames = new String[40];
        for (int i = 0; i < 40; i++) {
            soundnames[i] = "Sound " + i;
        }
        // Retrieve the list of position that are checked(if any) from the
        // database
        statusDb = mHelper.getWritableDatabase();
        Cursor statusCursor = statusDb.rawQuery("SELECT * FROM status", null);
        int[] savedStatus = null;
        if ((statusCursor != null) & (statusCursor.moveToFirst())) {
            savedStatus = new int[statusCursor.getCount()];
            int i = 0;
            do {
                savedStatus[i] = statusCursor.getInt(0);
                i++;
            } while (statusCursor.moveToNext());
        }
        // if the cursor is null or empty we just pass the null savedStatus to
        // the adapter constructor and let it handle(setting all the CheckBoxes
        // to unchecked)
        setListAdapter(new MobileArrayAdapter(this, soundnames, savedStatus));
    }

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

        @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.adapters_simpleplay_row,
                        parent, false);
            }
            CheckBox cBox = (CheckBox) rowView.findViewById(R.id.checkBox1);
            cBox.setTextColor(0xFFFFFFFF);
            cBox.setText(values[position]);
            cBox.setTag(new Integer(position));
            cBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                        boolean isChecked) {
                    int realPosition = (Integer) buttonView.getTag();
                    if (isChecked) {
                        itemChecked.set(realPosition, true);
                        // update the database to store the new checked item:
                        ContentValues cv = new ContentValues();
                        cv.put("list_position", realPosition);
                        statusDb.insert("status", null, cv);
                    } else {
                        itemChecked.set(realPosition, false);
                        // delete this position from the database because it was
                        // unchecked
                        statusDb.delete("status", "list_position = "
                                + realPosition, null);
                    }
                }
            });
            cBox.setChecked(itemChecked.get(position));
            return rowView;
        }
    }

    //for working with the database
    private class Helper extends SQLiteOpenHelper {

        public Helper(Context context, String name, CursorFactory factory,
                int version) {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // the list_position will hold the position from the list that are
            // currently checked
            String sql = "CREATE TABLE status (list_position INTEGER);";
            db.execSQL(sql);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // Just for interface
        }

    }

}

快速测试后,代码工作。 这只是一个例子。



Answer 2:

你可以做一两件事采取相同大小的布尔数组和存储它是否被点击或不

您也可以使用另一个类来存储的选中状态...

这是接触的多个选择的示例中,这肯定有助于ü.....

联系方式的多选

编辑:

public class simple List extends ListActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setListAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_multiple_choice, GENRES));

    final ListView listView = getListView();

    listView.setItemsCanFocus(false);
    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}

private static final String[] GENRES = new String[] { "india", "england", "London", "New york", "New jercy", "LA", "Pakistan", "srilanka", "bangladesh", "chin", "Australia", "Japan" };}


文章来源: Storing CheckBox state in a ListView