【问题标题】:Unable to set custom colors inside ExpandableListView无法在 ExpandableListView 中设置自定义颜色
【发布时间】:2013-07-24 22:43:50
【问题描述】:

我是 Android 新手。

我正在尝试在 ExpandableListView 适配器中设置自定义颜色。我已经在 colors.xml 中定义了我的颜色,但是我无法在我的适配器中使用它们。我收到一个错误“ExpandableListAdapter 类型的方法 getResources() 未定义”

该函数需要一个 int。我试图从 getResources 中传递我的结果,但是它不起作用。我也尝试过传入一个十六进制值,但它并没有改变任何东西。

如何在我的代码中使用我的自定义颜色?

    public View getGroupView(int groupPosition, boolean arg1, View convertView,
        ViewGroup arg3) {
    int n = 0;
    String laptopName = (String) getGroup(groupPosition);
    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.group_item, null);
    }
    TextView item = (TextView) convertView.findViewById(R.id.demo);
    item.setTypeface(null, Typeface.BOLD);
    item.setText(laptopName);

    convertView.setBackgroundColor(getResources().getColor(R.color.purple));

    return convertView;
}

谢谢大家,下面的sn-p可以工作了

this.context = (Activity) context;
    convertView.setBackgroundColor(this.context.getResources().getColor(R.color.purple));

【问题讨论】:

    标签: android android-layout android-ui


    【解决方案1】:

    假设你在适配器的某个地方有一个上下文实例而不是这个

    convertView.setBackgroundColor(getResources().getColor(R.color.purple));
    

    应该是这样的

    convertView.setBackgroundColor((your context).getResources().getColor(R.color.purple));
    

    如果您没有对上下文的引用,只需将其传递给适配器构造函数

    【讨论】:

      【解决方案2】:

      正如 loulou8284 所提到的,您可以将它放在您的 XML 中,或者如果它已修复,则使用 Color.rgb() 定义它,但要使您的代码运行,您需要获取对您的 Context 的引用,因为您的类没有在上下文类:

      convertView.setBackgroundColor(getContext().getResources().getColor(R.color.purple));
      

      【讨论】:

      • 行不通。我得到:错误“ExpandableListAdapter 类型的方法 getContext() 未定义”
      • 这是因为您不能在适配器中调用该方法
      【解决方案3】:

      您可以在 .xml 文件中声明颜色(在您的项目 xml 文件中)

      【讨论】:

        【解决方案4】:

        使用setBackgroundResource() 而不是setBackgroundColor()

        setBackgroundResource() 将整数资源索引作为参数,并加载索引指向的任何资源(例如;可绘制对象、字符串或在您的情况下为颜色)。

        setBackgroundColor(),但是需要一个表示颜色的整数。也就是说,不是颜色资源,而是直接的十六进制 rgba 值 (0xAARRGGBB)。

        【讨论】:

          猜你喜欢
          • 2014-10-30
          • 2016-07-19
          • 1970-01-01
          • 1970-01-01
          • 2020-04-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多