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="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" 
    android:drawable="@drawable/home_image_select" /> 
<item android:state_selected="false" 
    android:drawable="@drawable/home_image" /> 
</selector>

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(R.id.gallery_image)).setSelected(true);

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

Solution

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

 @Override
public void setSelection(int position) {
    super.setSelection(position);

View v = this.getAdapter().getView(position, null, this);
    v.setFocusable(true);
    v.requestFocus();
}

Related Problems and Solutions