【问题标题】:how to bind a checkbox to a listview如何将复选框绑定到列表视图
【发布时间】:2014-01-24 06:21:15
【问题描述】:

我有一个列表视图,每行都包含一个带有复选框的文本视图,所以当复选框被选中并且我们向下滚动列表视图时,复选框实例将从一个地方带到另一个地方(重用..),我有几个选中的复选框如何解决我试图将复选框绑定到列表视图但不起作用我的代码是:

 SimpleCursorAdapter adapter =new SimpleCursorAdapter(this,R.layout.rating,cu,new String[]{"Title","Favorites"}, new int[]{R.id.text1,R.id.bt_rating},CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        listv.setAdapter(adapter);

        adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder(){
               /** Binds the Cursor column defined by the specified index to the specified view */
               public boolean setViewValue(View view, Cursor cursor, int columnIndex){
                   if(view.getId() == R.id.bt_rating){

                      ((CheckBox)view).setChecked(Boolean.valueOf(cursor.getString(cursor.getColumnIndex("Favorites"))));
                      ((CheckBox)view).setOnCheckedChangeListener(myCheckChangList);
                       return true; //true because the data was bound to the view
                   }
                   return false;
               }
            });


 OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                 buttonView.setChecked(isChecked);
            }
        };

我的listview行内容的xml代码是:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

  <CheckBox
 android:id="@+id/bt_rating"
 android:focusable="false"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="center_vertical"
 android:button="@android:drawable/btn_star"/>

<TextView

android:id="@+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="@dimen/fsinlistview"

 />
</LinearLayout>

【问题讨论】:

标签: android listview simplecursoradapter android-viewbinder


【解决方案1】:

在任何 Listview 中,视图都被重用。当您滚动浏览列表时,那些向上滚动和离开屏幕的内容会被回收并与下面出现的更新信息一起使用。

您需要使用稀疏数组来跟踪您的复选框。当用户触摸每个索引时,将数组中的索引标记为 cherked/unchecked。然后根据数组中的值设置复选框的状态。

这是来自旧应用程序的一些示例代码,它既可以“全选”复选框,也可以管理选中和未选中的整个列表。这是我写的一个课堂考勤应用程序,所以老师更容易选择“所有”在课堂上,然后取消选择那些不在场的人。

我在这个列表视图中有两个复选框,以及两个稀疏数组 itemCheckedHere 和 itemCheckedLate(学生是否在上课或迟到)。

public class MyDataAdapter extends SimpleCursorAdapter {
    private Cursor c;
    private Context context;
    private Long classnum;
    private gradeBookDbAdapter mDbHelper;

    public static final int LATE=2;
    public static final int ATTEND=1;
    int idxCol;
    int idx;

    // itemChecked will store the position of the checked items.

    public MyDataAdapter(Context context, int layout, Cursor c, String[] from,
            int[] to, Long mRowId) {
        super(context, layout, c, from, to);
        this.c = c;
        this.context = context;
        mDbHelper = new gradeBookDbAdapter(context);
        mDbHelper.open();
        classnum = mRowId;
        c.moveToFirst();



    }
    public class ViewHolder{
        public TextView text;
        public TextView text2;
        public ImageView image;
        public CheckBox here;
        public CheckBox late;
    }


    public View getView(final int pos, View inView, ViewGroup parent) {
        Bitmap bm;
        ImageView studentPhoto;
        View vi=inView;
        final ViewHolder holder;

        if (inView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            vi = inflater.inflate(R.layout.show_attendance, null);

            holder=new ViewHolder();
            holder.text=(TextView)vi.findViewById(R.id.stuname);
            holder.text2=(TextView)vi.findViewById(R.id.stuIndex);
            holder.image=(ImageView)vi.findViewById(R.id.icon);
            holder.here=(CheckBox)vi.findViewById(R.id.attend);
            holder.late=(CheckBox)vi.findViewById(R.id.late);
            vi.setTag(holder);

        }
        else
           holder=(ViewHolder)vi.getTag();


        c.moveToPosition(pos);
        int index = c.getColumnIndex(gradeBookDbAdapter.KEY_NAME);
        String name = c.getString(index);
        holder.text.setText(name);
        index = c.getColumnIndex(gradeBookDbAdapter.KEY_ROWID); 
        String Index = c.getString(index);
        holder.text2.setText(Index);

        bm = gradeBookDbAdapter.getStudentPhoto(name);
        if (bm != null) {
            holder.image.setImageBitmap(bm);  
        }           
        else {
            // use icon image
            holder.image.setImageResource(R.drawable.person_icon);
        }


        // pull out existing attend/late fields and set accordingly
        int attend = c.getInt(c.getColumnIndex(gradeBookDbAdapter.KEY_ATTEND));
        if(attend==1){
           holder.here.setChecked(true);
           itemCheckedHere.set(pos, true);
        }
        //else {
        //   holder.here.setChecked(false);
        //   itemCheckedHere.set(pos, false);
        //}

        int late = c.getInt(c.getColumnIndex(gradeBookDbAdapter.KEY_LATE));
        if (late==1){
           holder.late.setChecked(true);
           itemCheckedLate.set(pos, true);
        }
        //else {
        //  holder.late.setChecked(false);
        //    itemCheckedLate.set(pos, false);
        //}


        if (selectAllTouched) {
            if(selectAll){
                holder.here.setChecked(true);
                itemCheckedHere.set(pos, true);
                int who= new Integer(holder.text2.getText().toString());
                mDbHelper.updateAttend(who, classnum, ATTEND, 1, attendDate );
            }
            else{
                holder.here.setChecked(false);
                itemCheckedHere.set(pos, false);
                int who = new Integer(holder.text2.getText().toString());
                mDbHelper.updateAttend(who, classnum, ATTEND, 0, attendDate );
            }
        }


        holder.here.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

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

                if (cb.isChecked()) {
                    itemCheckedHere.set(pos, true); 
                    int Index = new Integer(holder.text2.getText().toString());
                    mDbHelper.updateAttend(Index, classnum, ATTEND, 1, attendDate ); 
                } else if (!cb.isChecked()) {
                    itemCheckedHere.set(pos, false);
                    int Index = new Integer(holder.text2.getText().toString());
                    mDbHelper.updateAttend(Index, classnum, ATTEND, 0, attendDate );
                }
            }
        });
        holder.late.setOnClickListener(new OnClickListener() {

           public void onClick(View v) {
                CheckBox cb = (CheckBox) v.findViewById(R.id.late);

                if (cb.isChecked()) {
                   itemCheckedLate.set(pos, true);
                   int Index = new Integer(holder.text2.getText().toString());
                   mDbHelper.updateAttend(Index, classnum, LATE, 1, attendDate );
                } else if (!cb.isChecked()) {
                   itemCheckedLate.set(pos, false);
                   int Index = new Integer(holder.text2.getText().toString());
                   mDbHelper.updateAttend(Index, classnum, LATE, 0, attendDate );
                }
            }
        });


        holder.here.setChecked(itemCheckedHere.get(pos)); // this will Check or Uncheck the
        holder.late.setChecked(itemCheckedLate.get(pos)); // 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 vi;
    }

}

}

【讨论】:

  • 非常感谢马丁,但这段代码与我的不同,如果我用完了解决方案就会看到它:)
  • 是的,它和你的不一样。我的目的不是为您编写代码,而是提供一个如何处理列表视图中的复选框的示例。如果您正在寻找可以简单地放入您的项目的即插即用代码,我需要先给您我的 paypal 帐户,您可以在其中为我的努力付钱。
【解决方案2】:

看来您的OnCheckedChangedListener 是这里的问题。如果您查看您的代码,会发现 every 复选框正在获取对 same 侦听器的引用。因此,当您选中一个框时,您也将其他所有框都设置为已选中 - 而且您也不会更新您的支持数据。

您的 OnCheckedChangedListener 不应更新复选框的视图状态 - 因为状态已更改,所以触发回调。

所以当用户勾选复选框时,您需要执行以下步骤:

  1. 找出检查了哪个项目,以及它与您的数据的对应关系
  2. 更新您的数据以适应新的选中/未选中状态
  3. 通知您的适配器数据更改/更新您的光标

您可以执行以下操作,使用它所代表的行的 ID 标记视图:

public boolean setViewValue(View view, Cursor cursor, int columnIndex){
    if(view.getId() == R.id.bt_rating){
        view.setTag(cursor.getInt(cursor.getColumnIndex(SomeDBContract.ID)));
        ((CheckBox)view).setChecked(Boolean.valueOf(cursor.getString(cursor.getColumnIndex("Favorites"))));
        ((CheckBox)view).setOnCheckedChangeListener(myCheckChangList);
        return true; //true because the data was bound to the view
    }
    return false;
}

然后,在您的侦听器中,您可以根据该 ID 更新您的数据库:

CheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
             int rowId = (int) buttonView.getTag();
             // Handle updating the database as per normal
             updateSomeDbRowAsChecked(rowId, isChecked);
        }
    };

最后,一旦数据库行更新,您需要使用新游标更新游标适配器:

 myAdapter.swapCursor(newCursor);

您必须调整所有这些以适合您的代码,但它应该让您了解解决此问题的一种方法。

【讨论】:

  • 好的会解决这个问题,但我的 viewbinder 也没有被调用,因为我在其中放置了一个 log.d 并且它没有被调用..
  • 也只是直接添加了监听器的内容来检查结果,我需要做的就是将更改添加到我的数据库中;但是为什么 viewbinder 没有被调用?
  • 我不确定,抱歉 - 设置视图活页夹的代码看起来是正确的。
  • 是的,我在适配器中有错误,我没有在其中添加 bt_rating,这就是为什么现在它正在访问活页夹但仍然得到不正确的结果,如果上帝愿意的话,稍后会检查原因......谢谢。跨度>
猜你喜欢
  • 2015-09-11
  • 1970-01-01
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
  • 2013-11-25
  • 1970-01-01
  • 2017-05-06
相关资源
最近更新 更多