Question

I have extended the Android ListView component to be able to make changes to its list items when they are clicked and to make the first item selected per default.

The problem is that when making changes to the list items by adding an OnItemClickListener, this event is not fired when an Activity overrides it. How can this behavior be set to always happen no matter if the event is overridden or not?

In relation to the above, I would also like that these changes are added to the first item in the list when initialized (as a default selection). I have been looking everywhere for a solution. Some of the things I have tried includes experimenting with setSelection(0), setSelected(true), setActivated(true) and setItemChecked(0, true). I have also been trying to use performClick(), but this trows NullPointerException. To indicate a click I'm using a StateListDrawable added as android:background to the list item.

StateListDrawable:

<selector xmlns:android="http://schemas.android.com/apk/res/android"
          android:exitFadeDuration="@android:integer/config_longAnimTime">
    <item android:drawable="@android:color/holo_orange_dark" android:state_pressed="true"/>
    <item android:drawable="@color/list_active" android:state_selected="true"/>
    <item android:drawable="@color/list_active" android:state_activated="true"/>
    <item android:drawable="@color/list_active" android:state_checked="true"/>
    <item android:drawable="@color/list_background"/>
</selector>

It should also be noted that I'm using a custom adapter for the listview, even though it is not doing anything else than adding contents to the list item.

A short excerpt of the custom listview code:

public class ShadowListview extends ListView {

    public ShadowListView(Context context) {
        super(context);
        init();
    }

    ...

    private void init() {
        setOnItemClickListener(new ShadowListViewClicker());
    }

    private class ShadowListViewClicker implements OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // Handling changes to items here
            ...
        }
    }

}

Any help to my issues are greatly appreciated, since I'm starting to loose my hair working on this :)

Was it helpful?

Solution

I would handle it all in the adapter, maintain an integer representing the selected index, defaulted to 0. Modify your getView to render the view differently if the index matches the selected index. Provide a public setSelected(int) method in the adapter that will update the selected index and call notifyDataSetChanged() to refresh the list. In your onItemClick method call setSelected on the adapter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top