在ListView存储复选框的状态 [英] Storing CheckBox state in a ListView

查看:129
本文介绍了在ListView存储复选框的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一张code,我发现存储的复选框是在的ListView <国家/ code>,但它并没有奏效。没有人有任何想法,为什么从我的适配器我的code不工作?

 包kevin.erica.box;

进口的java.util.ArrayList;

进口kevin.erica.box.R;

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

公共类MobileArrayAdapter扩展ArrayAdapter&LT;字符串&GT; {
    私人最终上下文的背景下;
    私人最终的String []值;
    私人的ArrayList&LT;布尔&GT; itemChecked =新的ArrayList&LT;布尔&GT;();

    公共MobileArrayAdapter(上下文的背景下,的String []值){
        超(背景下,R.layout.list_adapter,价值观);
        this.context =背景;
        this.values​​ =值;

        的for(int i = 0; I&LT; this.getCount();我++){
            itemChecked.add(我,FALSE); //初始化所有的物品为FALSE
        }
    }


    @覆盖
    公共查看getView(最终诠释的立场,观点covertView,ViewGroup中父){
        LayoutInflater充气=(LayoutInflater)上下文
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            查看rowView = inflater.inflate(R.layout.list_adapter,父母,假);
            复选框的TextView =(复选框)rowView.findViewById(R.id.checkBox1);
            textView.setTextColor(0xFFFFFFFF的);
            textView.setText(值[位置]);
            //存储状态的尝试
            最终的复选框的CBox =(复选框)rowView.findViewById(R.id.checkBox1); //你
            //复选框
            cBox.setOnClickListener(新OnClickListener(){

                公共无效的onClick(视图v){

                复选框CB =(复选框)v.findViewById(R.id.checkBox1);

                如果(cb.isChecked()){
                    itemChecked.set(位置,真正的);
                    //这里做一些操作
                }否则如果(!cb.isChecked()){
                    itemChecked.set(位置,假);
                    //这里做一些操作
                }
            }
        });
        cBox.setChecked(itemChecked.get(位置)); //这会选中或取消
        //复选框中的ListView
        //按其原来
        //位置和CheckBox永远
        //损失他的状态,当你
        //滚动列表项。
        返回rowView;
    }
}
 

解决方案

您的问题没有说关于存储数据后,该应用程序已关闭任何东西。要存储检查复选框您可以使用一个数据库或简单的文件。贝娄是存储复选框的状态在一个数据库中的一个例子:

 公共类SimplePlay扩展ListActivity {

    私有String [] soundnames;
    私人助手mHelper =新的助手(这一点,position_status.db,NULL,1);
    私人SQLiteDatabase statusDb;

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        //这是模拟数据
        soundnames =新的String [40];
        的for(int i = 0; I&LT; 40;我++){
            soundnames [I] =声音+我;
        }
        //获得的位置被选中(如果有的话)从名单
        // 数据库
        statusDb = mHelper.getWritableDatabase();
        光标s​​tatusCursor = statusDb.rawQuery(SELECT * FROM状态,NULL);
        INT [] savedStatus = NULL;
        如果((statusCursor = NULL)及!(statusCursor.moveToFirst())){
            savedStatus =新INT [statusCursor.getCount()];
            INT I = 0;
            做 {
                savedStatus [I] = statusCursor.getInt(0);
                我++;
            }而(statusCursor.moveToNext());
        }
        //如果光标为null或空,我们只是通过空savedStatus到
        //适配器的构造,并让它处理(将所有的复选框
        //为未选中)
        setListAdapter(新MobileArrayAdapter(这一点,soundnames,savedStatus));
    }

    公共类MobileArrayAdapter扩展ArrayAdapter&LT;字符串&GT; {
        私人最终上下文的背景下;
        私人最终的String []值;
        私人的ArrayList&LT;布尔&GT; itemChecked =新的ArrayList&LT;布尔&GT;();

        公共MobileArrayAdapter(上下文的背景下,的String []值,
                INT [] oldStatus){
            超(背景下,R.layout.adapters_simpleplay_row,价值观);
            this.context =背景;
            this.values​​ =值;

            //通过oldStatus使每一个复选框选中,然后循环(如果
            // NOT NULL)
            的for(int i = 0; I&LT; this.getCount();我++){
                itemChecked.add(我,FALSE);
            }
            如果(oldStatus!= NULL){
                对于(INT J = 0; J&LT; oldStatus.length; J ++){
                    itemChecked.set(oldStatus [J],真正的);
                }
            }
        }

        @覆盖
        公共查看getView(最终诠释的立场,观点convertView,
                ViewGroup中父){
            查看rowView = convertView;
            如果(rowView == NULL){
                LayoutInflater充气=(LayoutInflater)上下文
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                rowView = inflater.inflate(R.layout.adapters_simpleplay_row,
                        父母,假);
            }
            复选框的CBox =(复选框)rowView.findViewById(R.id.checkBox1);
            cBox.setTextColor(0xFFFFFFFF的);
            cBox.setText(值[位置]);
            cBox.setTag(新的整数(位置));
            cBox.setOnCheckedChangeListener(新OnCheckedChangeListener(){

                @覆盖
                公共无效onCheckedChanged(CompoundButton buttonView,
                        布尔器isChecked){
                    INT realPosition =(整数)buttonView.getTag();
                    如果(器isChecked){
                        itemChecked.set(realPosition,真正的);
                        //更新存储新签项目数据库:
                        ContentValues​​ CV =新ContentValues​​();
                        cv.put(list_position,realPosition);
                        statusDb.insert(状态,空,CV);
                    } 其他 {
                        itemChecked.set(realPosition,假);
                        //从数据库中删除这个位置,因为它是
                        //选中
                        statusDb.delete(状态,list_position =
                                + realPosition,NULL);
                    }
                }
            });
            cBox.setChecked(itemChecked.get(位置));
            返回rowView;
        }
    }

    //与数据库工作
    私有类辅助扩展SQLiteOpenHelper {

        公共助手(上下文的背景下,字符串名称,CursorFactory厂,
                INT版){
            超(背景下,名称,厂家,版本);
        }

        @覆盖
        公共无效的onCreate(SQLiteDatabase DB){
            //该list_position将举行从列表中的位置
            目前检查//
            字符串SQL =CREATE TABLE状态(list_position整数);
            db.execSQL(SQL);
        }

        @覆盖
        公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
            //只是接口
        }

    }

}
 

在快速测试中,code工作。这仅仅是一个例子。

I'm trying to implement a piece of code I found to store the state of a CheckBox that is in a ListView but it didn't worked. Does anyone have any idea why my code from my adapter isn't working?

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

解决方案

You question didn't say anything about storing the data after the application has closed. To store the checked CheckBoxes you could use a database or a simple file. Bellow is an example of storing the CheckBox state in a database:

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
        }

    }

}

After a quick test, the code works. It is just an example.

这篇关于在ListView存储复选框的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆