2013-07-30 80 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