Android: custom gallery settings setSelection ()

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

When I first start my activity, I want to call setSelection(position) to make ImageView change its selector to the "selected" image. This works when I drop the gallery on subsequent selected children, but not the first time the application starts.

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 assumption was to call notifyDataSetChanged () on the adapter after calling setSelection (), which I tried to do as follows:

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

It did nothing. I also tried to override 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); 

This does not work either. Is there something I am missing or can I try?

+4
source share
2 answers

I found a solution to my problem by overwriting setSelection () in the gallery (this still worked).

  @Override public void setSelection(int position) { super.setSelection(position); View v = this.getAdapter().getView(position, null, this); v.setFocusable(true); v.requestFocus(); } 
0
source

I think you should not call notifyDataSetChanged() , the selection state will be cleared when the underlying dataset changes.

Just call setSelection(position) , it works in my application.

0
source

Source: https://habr.com/ru/post/1393416/


All Articles