Java – Android: Custom gallery setSelection() issue

Android: Custom gallery setSelection() issue… here is a solution to the problem.

Android: Custom gallery setSelection() issue

I have an extended BaseAdapter with LinearLayout subitems connected to the custom gallery (one ImageView and one TextView in each).

When I first start my activity, I want to call setSelection(position) to make ImageView change its selector to “selected” images. This works once I convert the gallery onto the subsequently selected subkeys, but not the first time I launch the application.

My selector:

<selector xmlns:android="">
<item android:state_selected="true" 
    android:drawable="@drawable/home_image_select" /> 
<item android:state_selected="false" 
    android:drawable="@drawable/home_image" /> 

My first guess was to call notifyDataSetChanged() on the adapter after calling setSelection(), which I tried to do:

((CustomAdapter) gallery.getAdapter()).notifyDataSetChanged();

That didn’t do anything. I also tried overriding setSelection() of the Gallery class to do this:

View v = this.getAdapter().getView(position, null, this);       
((ImageView) v.findViewById(;

That doesn’t work either. Is there anything I missed or can try?


I found a solution to my own problem by overriding the gallery’s setSelection() (it worked, after all).

public void setSelection(int position) {

View v = this.getAdapter().getView(position, null, this);

Related Problems and Solutions