Android 无法在ExpandableListView中设置自定义颜色

Android 无法在ExpandableListView中设置自定义颜色,android,android-layout,android-ui,Android,Android Layout,Android Ui,我是个Android新手 我正在尝试在ExpandableListView适配器中设置自定义颜色。我已在colors.xml中定义了颜色,但无法在适配器中使用它们。我得到一个错误“类型ExpandableListAdapter的getResources()方法未定义” 该函数需要一个int。我已尝试将getResources的结果传入,但它不起作用。我也试着传入一个十六进制值,但它没有改变任何东西 如何在代码中使用自定义颜色 public View getGroupView(int gr

我是个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;
}
谢谢大家,下面的代码片段很有用

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

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

如Lou8284所述,您可以将其放入xml中,或者如果它是固定的,则使用
color.rgb()
定义它,但要使代码运行,您需要获得对上下文的引用,因为您的类未在上下文类中声明:

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

假设您在适配器中的某个位置有一个上下文实例,而不是此实例

convertView.setBackgroundColor(getResources().getColor(R.color.purple));
应该是这样

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

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

使用
setBackgroundResource()
而不是
setBackgroundColor()

setBackgroundResource()将整数资源索引作为参数,并加载索引指向的任何资源(例如,可绘制的、字符串或颜色)


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

不行。我得到:一个错误“类型ExpandableListAdapter的方法getContext()未定义”,因为您不能在适配器中调用该方法