androidandroid-listfragment

Listview items are not clickable


I use 'ListFragment' to list items in a listview. The listview's xml is:

<ListView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:id="@android:id/list"
    android:layout_weight="1"
    android:dividerHeight="4dp" />

And the XML layout for the items is:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/fromId"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:visibility="gone" />

<TextView
    android:id="@+id/fromName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:singleLine="false"
    android:layout_weight="1" />

<TextView
    android:id="@+id/toId"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:visibility="gone" />

<TextView
    android:id="@+id/toName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:singleLine="false"
    android:layout_weight="1"/>
</LinearLayout>

I also have the the following in the fragment:

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    MyItem item = (MyItem)l.getItemAtPosition(position);
}

However, the items are not clickable.

What am I missing?


Solution

  • Did you try with

        ListView listView = getListView();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(getActivity().getBaseContext(), "Item clicked: " +  [position], Toast.LENGTH_LONG).show();
                // Your Staff
            }
        });
    

    Or

     getListView().setOnItemClickListener(this); // onActivityCreated()
    
    
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
    
            Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT)
                    .show();
    
        }
    

    Edited

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Toast.makeText(getActivity().getBaseContext(), "Item clicked: " +  [position], Toast.LENGTH_LONG).show();
            MyItem item = (MyItem)l.getItemAtPosition(position);
        }