Search code examples
javaandroidandroid-widgetandroid-galleryandroid-adapter

Android: Custom Gallery setSelection() issues


I have an extended BaseAdapter that has LinearLayout children (an ImageView and a TextView in each) hooked up to a custom Gallery.

When I first launch my Activity, I want to call setSelection(position) to cause the ImageView to change its selector to the "selected" image. This works once I fling the Gallery, on subsequent selected children, but not the very first time the app is launched.

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 attempted to do like this:

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

That didn't do anything. I also tried overriding the 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. Anything I'm missing or could try?


Solution

  • I found the solution to my own problem by overwriting the setSelection() of Gallery (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();
    }