【问题标题】:Android 4.4.2 - Background colors not set on spinnerAndroid 4.4.2 - 微调器上未设置背景颜色
【发布时间】:2016-06-18 06:47:59
【问题描述】:

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

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

ma​​in_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) {
        }
    });
}

文字故意为白色,与背景形成对比。

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

build.gradle

    minSdkVersion 16
    targetSdkVersion 16

有人知道我该如何解决这个问题吗?

谢谢!

朱塞佩

回答: 我应该改用 setBackgroundResource 并在 colors.xml 文件中定义颜色

【问题讨论】:

  • 从 Spinner 中选择项目后,您是要更改该特定项目的颜色还是要更改 Spinner 内整个文本的颜色
  • 我想根据选定的微调器项目更改背景颜色...

标签: android colors background-color


【解决方案1】:

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

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

为此

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

【讨论】:

  • 这不是关于文本颜色而是背景颜色...我阅读了更多内容,似乎我应该改用 setBackgroundResource 并在 colors.xml 文件中定义颜色:S
  • 是的,是同样的逻辑,只需将颜色添加到你的colors.xml中并按照这个方法。
  • 设置背景颜色也一样:view.setBackgroundColor(getResources().getColor(colorresid));
【解决方案2】:

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

【讨论】:

  • 微调器根据 strings.xml 中定义的项目动态膨胀,因此我不必更改布局中的任何内容...因此,背景颜色为在选择项目时在运行时确定
  • 您在创建后对阵列适配器所做的任何更改都不会生效。因此,您需要一个自定义适配器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-26
相关资源
最近更新 更多