I have a Gallery with text items. I can change the selected item with the UI or programmatically with setSelection(position). However when I call this method, sometimes the item background is not changed to a selected state. I noticed that if the item called by setSelection is already drawn on the screen then its background is not updated.
Here is the code. Any help is welcome.
public class Test3 extends Activity {
private static String[] items = {"0", "1", "2", "3", "4", "5"};
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
LinearLayout layout = new LinearLayout (this);
layout.setOrientation (LinearLayout.VERTICAL);
setContentView (layout);
final Gallery 开发者_Go百科gallery = new Gallery (this);
layout.addView (gallery);
gallery.setSpacing (0);
gallery.setAdapter (new Adapter (this));
gallery.setSelection (0);
ListView list = new ListView (this);
layout.addView (list);
list.setAdapter (new ArrayAdapter <String> (this,
android.R.layout.simple_list_item_1, items));
list.setOnItemClickListener (new OnItemClickListener () {
public void onItemClick (AdapterView <?> parent, View view, int position,
long id)
{
gallery.setSelection (position);
}
});
}
private class Adapter extends ArrayAdapter <String> {
public Adapter (Context context) {
super (context, android.R.layout.simple_gallery_item, items);
}
public View getView (int position, View convertView, final ViewGroup parent)
{
TextView view = new TextView (getContext ());
view.setText (getItem (position));
view.setBackgroundResource (R.drawable.gallery_background);
view.setGravity (Gravity.CENTER);
view.setLayoutParams (new Gallery.LayoutParams (Test3.this
.getWindowManager ().getDefaultDisplay ().getWidth () / 3,
Gallery.LayoutParams.FILL_PARENT));
return view;
}
}
}
gallery_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@drawable/highlight_selected" />
<item android:state_checked="true" android:drawable="@drawable/highlight_selected" />
<item android:state_focused="true" android:drawable="@drawable/highlight_selected" />
<item android:state_pressed="true" android:drawable="@drawable/highlight_pressed" />
<item android:drawable="@drawable/highlight_disabled" />
</selector>
Try invalidating
the gallery or notifyDataSetChanged
the galleries adapter.
精彩评论