我使用textview和checkbox作为listView的项目。我为listview编写的代码工作正常。但是当我在listview onclicklistener事件中添加了复选框时,现在就不起作用了。我在xml文件中使用此代码:
我的xml代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="5" >
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:id="@+id/textView_Item_Listview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:gravity="right"
android:padding="3dp"
android:textSize="25sp" />
</LinearLayout>
我的java代码:
private class Adapter_collection extends ArrayAdapter<String> {
public Adapter_collection(Context context, int resource, int textViewResourceId,
String[] name_collection_tbl_collection) {
super(context, resource, textViewResourceId, name_collection_tbl_collection);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.listview_items, parent, false);
TextView txt_item_list_collection = (TextView) row.findViewById(R.id.textView_Item_Listview);
CheckBox checkBox=(CheckBox)row.findViewById(R.id.checkBox_Item_Listview);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked ) {
Toast.makeText(getApplicationContext(), String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
txt_item_list_collection.setText(name_collection_tbl_collection[position]);
return row;
}
}
list_collections.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent goTo_SubjectsActivity = new Intent(Collection_List_Activity.this, Subjects_Activity.class);
startActivity(goTo_SubjectsActivity);
Intent_values.id_collection = id_tbl_collection[arg2];
}
});
答案 0 :(得分:2)
可能的原因是,如果您touchable elements
中有List_item
,则会阻止list_item
触摸,因此onItemclickListener
上的ListView
无法正常工作。
如果要将onClickListener实现到ListView,可以添加
android:descendantFocusability="blocksDescendants"
位于list_item
LinearLayout
父级
答案 1 :(得分:1)
尝试将onclicklistener分配给textview,而不是列表。
private class Adapter_collection extends ArrayAdapter<String> {
...
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.listview_items, parent, false);
TextView txt_item_list_collection = (TextView) row.findViewById(R.id.textView_Item_Listview);
//add this
txt_item_list_collection.setOnClickListener(new OnClickListener() { ... });
txt_item_list_collection.setText(name_collection_tbl_collection[position]);
return row;
}
}