在微调器中更改所选项目的颜色

时间:2014-07-10 08:30:28

标签: android spinner android-spinner

由于某种原因,我的微调器中所选项目的文本颜色为白色。这是活动的代码:

spinner = (Spinner) findViewById(R.id.spinner_categories);
arr_list_categories = manager.get_all_categories();
arr_list_categories_names = new ArrayList<String>();
// Loop through the Categories array
for (int i = 0; i < arr_list_categories.size(); i++) 
{
    Category curr_category = arr_list_categories.get(i); // Get the Category object at current position
    arr_list_categories_names.add(curr_category.getCategory_name()
            .toString()); // Add the name of the Category to the Names Array        
}
// Setting the Adapter, to display retrieved data in the Spinner
adapter=new ArrayAdapter<String> (this, R.layout.simple_spinner_item, arr_list_categories_names);
// Setting the display source for the Spinner View
adapter.setDropDownViewResource(R.layout.simple_spinner_item);
// Populating the Spinner
spinner.setAdapter(adapter);
// Registering for On Item Selected listener
spinner.setOnItemSelectedListener(spinnerListener);

这是simple_spinner_item的XML:

<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="left"
    android:padding="5dip"
    android:textColor="#FF0000"
    android:textSize="20sp" />

下拉项目显示为红色,但不显示所选项目。我尝试将XML中的textColor更改为选择器:android:textColor="@drawable/spinner_text_color_selector"并创建了这个选择器:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="#FF0000"/><!-- pressed -->
    <item android:state_focused="true" android:color="#FF0000"/><!-- focused -->
    <item android:state_selected="true"  android:color="#FF0000"/>
    <item android:state_activated="true" android:color="#FF0000"/>
    <item android:color="#FF0000"/><!-- default -->
</selector>

但所选项目的文字颜色仍为白色。所以我尝试在OnItemSelectedListener中执行此操作:

TextView selected_tv = (TextView) parent.getChildAt(0);
selected_tv.setTextColor(Color.BLUE);

还是白......

为什么会发生这种情况?如何解决?谢谢!

1 个答案:

答案 0 :(得分:0)

TextView selected_tv = (TextView) parent.getChildAt(0);
selected_tv.setTextColor(Color.BLUE);

在此代码中,更改第一行(使用TextView的id):

TextView selected_tv = (TextView) parent.findViewById(R.id.selected_tv);
selected_tv.setTextColor(Color.BLUE);
相关问题