2011-07-15 28 views
0

我有一個包含文本項目的圖庫。我可以使用UI更改所選項目,或者使用setSelection(位置)以編程方式更改。但是,當我調用此方法時,有時項目背景不會更改爲選定狀態。我注意到,如果setSelection調用的項目已經在屏幕上繪製,那麼它的背景不會更新。圖庫項目背景未隨set更改選擇

這是代碼。歡迎任何幫助。

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 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> 
+0

仍然打開一個更清潔的解決方案。 – Patrick

回答

1

嘗試invalidating畫廊或notifyDataSetChanged畫廊適配器。

+0

我嘗試invalidate和refreshDrawableState沒有運氣......但它適用於'((ArrayAdapter )gallery.getAdapter())。notifyDataSetChanged()'。我將這個答案標記爲有用,但在接受它之前稍等一會,因爲它對我來說看起來像是黑客... – Patrick

+0

是不是真的是黑客。 notifyDataSetChanged告訴視圖視圖適配器中的某些內容(非特定的)已更改,並且它應該可能會更新它自己。如果您添加或刪除了適配器項目,則可以刷新視圖。 – AedonEtLIRA

+0

是的,但在這種情況下,我沒有更改任何項目。 – Patrick