您的位置:首页 > 移动开发 > Android开发

安卓Android开发:listView+checkbox的简单实现

2017-05-01 16:27 393 查看
安卓Android开发:listView+checkbox的简单实现

项目要用到列表显示并实现每一个条目item的选择。参考网上的listView案例基本上都是在getview处用

holder 作tag来完成的。我用了一下但是在滚动过程中经常出现错乱。holder方案的思路就是只加载显

示部分的数据。这样做的优势是更高效,特别是item数据比较多的情况下。我这里用的方法是在调用数

据表格适配器Adapter时。直接加载全部item,这样listview如何滚动都不会错乱,更可靠。
在创建Adapter时循环调用makeItemView然后生成一个itemView[]数组。下面代码是我在网上找的,加工了一下。感谢原创者。

   private View makeItemView( String strTitle, String strText, String strCon, boolean 

isChecked, Bitmap bm) {

            LayoutInflater inflater = (LayoutInflater) select_report.this

                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            // 使用View的对象itemView与R.layout.item关联

            View itemView = inflater.inflate(R.layout.item, null);

            // 通过findViewById()方法实例R.layout.item内各组件

            TextView title = (TextView) itemView.findViewById(R.id.name);

            title.setText(strTitle);    //填入相应的值

            TextView text = (TextView) itemView.findViewById(R.id.time);

            text.setText(strText);

            TextView con = (TextView) itemView.findViewById(R.id.con);

            con.setText(strCon);

            ImageView image = (ImageView) itemView.findViewById(R.id.img);

            image.setImageBitmap(bm);

            CheckBox checkBox = (CheckBox) itemView.findViewById(R.id.checkBox);

            checkBox.setChecked(isChecked);

            return itemView;

        }

因为getView不做任何操作。如果你要遍历item。这个效率和holder方法是一样的。

  public View getView(int position, View convertView, ViewGroup parent) {

            return itemViews[position];//itemViews[position]下面要用到。

        }

第2个问题来了。如何知道哪些checkbox被勾选了?网上的方法是建一个表和checkbox对应。点击了

checkbox的同时也在表里做记录。要知道哪些被勾选直接查表。这个方法的优点是简单。而我采用直接读

checkbox状态的方法。这种方法我在网络上还没看到,算是原创吧。我的方法的优点是可靠。

要在listview中读取checkbox就要把itemView[]一层一层的掰开找到checkbox。

itemView就是一个ViewGroup。它里面还有ViewGroup。

  public void getcb() {

            for (int i = 0; i < listView.getCount(); i++) {

                ViewGroup vg = (ViewGroup) itemViews[i];

                ViewGroup vg1 = (ViewGroup) vg.getChildAt(1);

                ViewGroup vg2 = (ViewGroup) vg1.getChildAt(0);

                CheckBox cb = (CheckBox) vg2.getChildAt(3);

                Log.i("rrrrrr-getcb", i+" "+cb.isChecked());

            }

感谢网络上热心共享的人们。人人为我,我为人人。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐