ListView onClickListener() does not work after add

2019-02-06 08:59发布

问题:

I have a ListView (my_list.xml):

 <ListView
        android:id="@+id/my_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:choiceMode="singleChoice"
      />

The layout for each list item is (list_item.xml):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="10dp"
    >

    <ImageView 
          android:id = "@+id/my_icon" 
          android:layout_width ="wrap_content" 
          android:layout_height ="wrap_content"
          android:layout_centerVertical="true"  
     /> 
    <TextView 
         android:id="@+id/my_str" 
         android:layout_width="wrap_content" 
         android:layout_height = "wrap_content" 
         android:layout_toRightOf="@id/my_icon"
     /> 

     <!--This radio button makes the list item unselectable, why?-->
     <RadioButton 
         android:id="@+id/my_radio_btn"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_centerVertical="true"
         android:layout_alignParentRight="true"
         />
</RelativeLayout>

In Java code, I use SimpleAdapter for the list:

my_list = (ListView) findViewById(R.id.my_list);

SimpleAdapter adapter = new SimpleAdapter(context, getOptions(),
           R.layout.list_item, 
           new String[] { "icon1","str1" }, 
           new int[] {R.id.my_icon, R.id.my_str });

my_list.setAdapter(adapter);

//onClickListener does not work after I added RadioButton in list item layout
my_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            Log.v("SELECTED", position+""); 
        }
    });

As you see, in above code, in the list item layout, I added a RadioButton, after I added this button, my list onClickListener does not work anymore, why?? (It works if it's without RadioButton on list item layout)

回答1:

Set the following properties to your RadioButton:

android:focusable="false"
android:focusableInTouchMode="false"

and in your OnItemClickListener, you need to set the radio button's checked flag by code.


Set you ListView as below:

<ListView
  android:id="@+id/my_list"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" />


回答2:

add this code to your RadioButton XML code:

android:focusable="false"
android:focusableInTouchMode="false"

Another keyword to solve this problem is TouchDelegate.

Edit:

https://stackoverflow.com/a/5528945/1285331