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

どのリストビューでも、ビューは再利用されます。リストをスクロールすると、画面を上下にスクロールしたものはリサイクルされ、下に来る新しい情報とともに使用されます。

スパース配列を使用してチェックボックスを追跡する必要があります。ユーザーがそれぞれに触れると、配列内のインデックスを cherked/unchecked としてマークします。次に、配列の値に基づいてチェックボックスの状態を設定します。

これは、「すべて選択」チェックボックスを実行するだけでなく、チェックされているものとチェックされていないもののリスト全体を管理する古いアプリのコード例です。それは私が書いた教室出席アプリ用だったので、教師が授業中の「すべて」を選択してから、出席していないものを選択解除する方がはるかに簡単でした.

このリストビューには 2 つのチェックボックスと、itemCheckedHere と itemCheckedLate (生徒が授業中か遅刻か) の 2 つのスパース配列があります。

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 に答える
0

OnCheckedChangedListenerここで問題があるようです。コードを見ると、すべてのチェックボックスが同じリスナーへの参照を取得していることがわかります。したがって、1 つのボックスをオンにすると、他のすべてのボックスもオンに設定され、バッキング データも更新されません。

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

コードに合わせてこれらすべてを調整する必要がありますが、この問題に対処する方法の 1 つがわかるはずです。

于 2014-01-06T19:58:44.040 に答える