Android 4.4.2 - 未在微调器

时间:2016-03-04 13:45:05

标签: android colors background-color

我有一个自定义的微调器(简单的文本视图),因为我想有一个简单的解决方案来更改所选项目的背景颜色:

spinner_categories.xml

     <TextView xmlns:android="http://schemas.android.com/apk/res/android"
         android:id="@android:id/text1"
         android:layout_width="150sp"
         android:layout_height="40sp"
         android:textSize="16sp"
         android:gravity="center" />

项目通过自定义适配器充气,背景颜色根据所选项目而变化,颜色存储为sharedprefs

main_acitivity

    spinner = (Spinner) findViewById(R.id.spinner);
    // The spinner items are populated from strings.xml, array elements
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.categories, R.layout.spinner_categories);
    spinner.setAdapter(adapter);


    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        // it sets the background color of the textview based on the selected item
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            ((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
            sharedpref_colorCategory = getSharedPreferences(COLORS_CATEGORY, Context.MODE_PRIVATE);
            parent.getChildAt(0).setBackgroundColor(sharedpref_colorCategory.getInt(spinner.getAdapter().getItem(position).toString(), 0));
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
}

文本有意为白色,以与背景形成对比。

现在,当我在Samsung S5(Android 5.0 - API 21)或模拟器中安装它时,背景颜色正确显示,而华为Y360(Android 4.4.2 - API 19)的背景颜色总是如此白色,所以我看不到所选项目。 build.gradle已配置如下:

的build.gradle

    minSdkVersion 16
    targetSdkVersion 16

有谁知道如何解决这个问题?

谢谢!

朱塞佩

ANSWER : 我应该使用setBackgroundResource来定义colors.xml文件中的颜色

2 个答案:

答案 0 :(得分:0)

你需要获取颜色资源而不是传递ID,事实是Color.WHITE只返回资源的id而不是颜色资源,所以改变这一行:

((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);

这个

(TextView) parent.getChildAt(0)).setTextColor(getResources().getColor(android.R.color.white));

答案 1 :(得分:0)

您需要在适配器中设置TextView的属性。为此,您必须创建自定义适配器并在适配器的getCustomView方法中处理TextView属性。请参阅this示例。

相关问题