2013-07-30 79 views
1

我試圖以編程方式更改微調器的狀態樣式。動態更改微調器狀態

但是當我按下一個項目時,它們都被改變了! 之前,按一切都很好,顏色都不錯:

enter image description here

按下時,所有項目變成綠色: enter image description here

我在自定義適配器這樣做:

@Override 
public View getDropDownView(int position, View convertView, ViewGroup parent) { 

    //getting the views and all the stuff 

    StateListDrawable colorStateList = new StateListDrawable(); 
    colorStateList.addState(new int[] {android.R.attr.state_focused, android.R.attr.state_pressed}, new ColorDrawable(Color.BLACK)); 
    colorStateList.addState(new int[] {android.R.attr.state_focused        }, new ColorDrawable(Color.BLUE)); 
    colorStateList.addState(new int[] {        android.R.attr.state_pressed}, new ColorDrawable(Color.GREEN)); 
    colorStateList.addState(new int[] {               }, new ColorDrawable(Color.YELLOW)); 

    holder.container.setBackgroundDrawable(colorStateList); 

    return convertView; 
} 

這裏是我的自定義下拉式佈局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/spinner_container" 
android:layout_width="@dimen/icon_ligne_size" 
android:layout_height="@dimen/icon_ligne_size" 
android:layout_gravity="left" 
android:gravity="left" 
android:orientation="horizontal" > 

    <TextView 
     android:id="@+id/spinner_dir1" 
     android:layout_width="0dp" 
     android:layout_height="match_parent" 
     android:layout_weight="3" 
     android:gravity="center_vertical" 
     android:textAppearance="@android:style/TextAppearance.Medium" /> 

    <ImageView 
     android:id="@+id/spinner_arrow" 
     android:layout_width="0dp" 
     android:layout_height="wrap_content" 
     android:layout_gravity="left" 
     android:layout_weight="1" /> 

    <TextView 
     android:id="@+id/spinner_dir2" 
     android:layout_width="0dp" 
     android:layout_height="match_parent" 
     android:layout_weight="3" 
     android:gravity="center_vertical" 
     android:textAppearance="@android:style/TextAppearance.Medium" /> 

</LinearLayout> 

(我知道這是uggly但這只是用於測試)

+0

我不明白你的問題,你想要按下顏色時綠色?從你的代碼'colorStateList.addState(new int [] {android.R.attr.state_pressed},new ColorDrawable(Color.GREEN));'它看起來就是你想要的。 – Kai

+0

是的,這就是我想要的,但只有按下的項目,而不是所有的。我希望這更清楚。 – lost17

回答

1

使用下面的代碼在

getDropDownView

 mTextViewBackgroundListDrawable = new StateListDrawable(); 
     mTextViewBackgroundListDrawable.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(Color.BLACK)); 
     mTextViewBackgroundListDrawable.addState(new int[]{android.R.attr.state_focused}, new ColorDrawable(Color.BLACK)); 
     mTextViewBackgroundListDrawable.addState(new int[]{android.R.attr.state_enabled}, new ColorDrawable(0)); 

     textView.setBackgroundDrawable(mTextViewBackgroundListDrawable); 

申報 「mTextViewBackgroundListDrawable」 全局變量來在你的自定義適配器。

它解決了我的問題。希望這個幫助。

+1

不錯。這可以允許將'ColorStateList'轉換爲'StateListDrawable',你有時需要在狀態改變時改變TextView背景顏色。 – John