Android 更改微调器的文本颜色(显示的文本 - 不是微调器中的项目)

Android Change Text Color of Spinner (displayed text - not items in spinner)

除了一个屏幕,Spinner 需要有 'black' 文本。一个屏幕需要 Spinner 具有 'White' 颜色(所选项目和微调器项目的显示文本)。

为了更清晰起见,这里是图片。

我能够为微调器项目获取 'White' 颜色,但不能为选定的显示文本获取颜色。同样,我不想全局更改样式 - 只是这一个屏幕。这可能吗?

public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 
    int index = adapterView.getSelectedItemPosition();
    ((TextView) spinner.getSelectedView()).setTextColor(getResources().getColor(R.color.white));
}

创建 Spinner 时,必须为其提供适配器。如果您使用的是 android 开发人员的标准实现:

 Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        R.array.planets_array, android.R.layout.simple_spinner_item);

你可以做的是创建你自己的布局来表示所提供的选定项目文本并将其放入适配器中,你可以在那里提供 'textColor' 属性,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@android:id/text1"
      style="?android:attr/spinnerItemStyle"
      android:singleLine="true"
      android:textColor="@color/primary_blue"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:ellipsize="marquee"
      android:textAlignment="inherit"/>

如果您正在使用 ArrayAdapter.createFromResource(),请不要忘记将 TextView 与 android:id="@android:id/text1" 结合使用,这样该适配器就可以将数据绑定到您的布局。