這是我的代碼:setOnItemClickListener不工作在一個ListView
的ListView:
ListView lv;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.aller_layout, container, false);
lv = (ListView) rootView.findViewById(R.id.listView1);
CustomAdapter ca = new CustomAdapter(rootView.getContext(), R.layout.preflist_checkbox_layout, oggetti);
lv.setAdapter(ca);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position, long id){
Log.i("onclick", "si");
Toast.makeText(view.getContext(), "You clicked", Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
和適配器:
public class CustomAdapter extends ArrayAdapter<Oggetto>{
private Context context;
private Oggetto[] oggetti = null;
private int layoutid;
public CustomAdapter(Context context, int layoutid, Oggetto[] oggetti){
super(context, layoutid, oggetti);
this.context = context;
this.oggetti = oggetti;
this.layoutid = layoutid;
}
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(layoutid, parent, false);
}
Oggetto oggetto = oggetti[position];
CheckBox cb = (CheckBox) convertView.findViewById(R.id.pref_checkbox);
cb.setText(oggetto.nome);
cb.setChecked(oggetto.preferito == 1);
return convertView;
}
}
現在我只是想趕上點擊列表視圖中的複選框,但代碼不工作,因爲它應該,當我點擊任何元素時,Log或Toast都不顯示。
我哪裏錯了?
編輯:因爲好像是在XML的一個問題,我將添加ListView控件行的佈局:
<?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="vertical"
android:descendantFocusability="blocksDescendants">
<CheckBox
android:id="@+id/pref_checkbox"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_vertical"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:focusable="false"
android:focusableInTouchMode="false"/>
</LinearLayout>
最後我最後的評論爲你工作。 – Meghna
不,這是錯的。即使使用複選框,您也可以單擊列表項並選中複選框。 – Raghunandan
爲一個例子檢查這個http://stackoverflow.com/questions/18162931/android-get-selected-item-using-checkbox-in-listview-when-i-click-a-button。接受錯誤的答案 – Raghunandan