首页 > 解决方案 > 如何在Android中使用Java在每个项目中生成具有不同背景颜色的微调器?

问题描述

我想在 Java 中生成一个用于颜色选择的微调器,它在下拉时应该是这样的:

在此处输入图像描述

我的 Java 代码现在看起来像这样:

    final Spinner spinner = new Spinner(context);
    String[] colors = new String[]{"[1]", "[2]", "[3]", "[4]", "[5]", "[6]"};
    final List<String> colorsList = new ArrayList<>(Arrays.asList(colors));
    final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, colorsList) {
      @Override
      public View getDropDownView(int position, View convertView, ViewGroup parent) {
        View view = super.getDropDownView(position, convertView, parent);
        TextView tv = (TextView) super.getDropDownView(position, convertView, parent);
        Color color = Color.rgb(18,18,218);
        switch(position){
           case 0:
              color = Color.rgb(28,158,218); 
              break;
           case 1:
              color = Color.rgb(218,58,218); 
              break;
           case 2:
              color = Color.rgb(128,18,28); 
              break;
        }
        return view;
      }
    };

但现在没有显示颜色,全是白色。有什么更好的方法来做到这一点?

标签: javaandroidandroid-spinnerbackground-color

解决方案


而不是TextView设置BackgroundColorview. 除此之外,如果要为所选视图着色,则还必须覆盖getView. 检查以下:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    return getCustomView(position, convertView, parent);
}

@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
    return getCustomView(position, convertView, parent);
}

private View getCustomView(int position, View convertView, ViewGroup parent) {
    View view = super.getDropDownView(position, convertView, parent);

    if (position % 2 == 1) {
        view.setBackgroundColor(Color.parseColor("#FFC3C0AA"));
    }
    else {
        view.setBackgroundColor(Color.parseColor("#FFB5DCE8"));
    }

    return view;
}

输出:

在此处输入图像描述


推荐阅读