2

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

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

我的列表视图行内容的 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>
4

2 回答 2

0

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

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

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

于 2014-01-06T19:58:44.040 回答
0

在任何 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;
    }

}

}

于 2014-01-06T19:40:01.147 回答