リストビューでチェックボックスを使用したいと思い、下記のようなコードを書いたのですが、なぜか
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
がnullになってしまいます。
本来はリストビューをスクロールしたときにチェックがおかしくなる問題を解決しようとしているのですが、
checkBoxがnullになってしまうためコメントアウトした処理まで進むことができません。
同じレイアウトにある
textView = (TextView) convertView.findViewById(R.id.listTextView2);
が正常に取得できるのに対してなぜcheckBoxだけnullになるのかまったくわかりません。
カスタムしたアダプタの中のgetView
java
1public View getView(int position, View convertView, ViewGroup parent) { 2 // 特定の行(position)のデータを得る 3 final MyData item = (MyData)getItem(position); 4 5 // convertViewは使い回しされている可能性があるのでnullの時だけ新しく作る 6 if (null == convertView) { 7 convertView = layoutInflater_.inflate(R.layout.list_style, null); 8 } 9 10 CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkbox); 11// checkBox.setChecked(item.isSelected); 12 13 // イベントリスナーを設定 14// checkBox.setOnClickListener(new View.OnClickListener() { 15// @Override 16// public void onClick(View view) { 17 // boolean isChecked = ((CheckBox) view).isChecked(); 18 // item.setSelected(isChecked); 19// } 20// }); 21 22 TextView textView; 23 textView = (TextView) convertView.findViewById(R.id.listTextView2); 24 textView.setText(item.getData()); 25 26 return convertView;
リストビューに表示するリストのレイアウトです
xml
1<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:orientation="horizontal" 3 android:descendantFocusability="blocksDescendants" 4 android:layout_width="match_parent" 5 android:layout_height="wrap_content"> 6 7 <LinearLayout 8 xmlns:android="http://schemas.android.com/apk/res/android" 9 android:layout_width="match_parent" 10 android:layout_height="match_parent" 11 android:layout_weight="1" 12 android:orientation="vertical"> 13 14 <TextView 15 android:id="@+id/listTextView1" 16 android:layout_width="match_parent" 17 android:layout_height="wrap_content" 18 android:textColor="#000000" 19 android:textSize="16sp" 20 android:paddingBottom="4dp" /> 21 22 <TextView 23 android:id="@+id/listTextView2" 24 android:layout_width="match_parent" 25 android:layout_height="wrap_content" 26 android:textColor="#000000" 27 android:textSize="18sp" /> 28 29 </LinearLayout> 30 31 <CheckBox 32 android:layout_width="wrap_content" 33 android:layout_height="match_parent" 34 android:id="@+id/checkBox" /> 35</LinearLayout>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/03/12 04:15
2016/03/12 10:20