简体   繁体   English

setBackgroundColor(drawable)!= android:background =(drawable)?

[英]setBackgroundColor(drawable) != android:background=(drawable)?

I've got a custom drawable resource to display my items in a ListView, actually two because I wanted my results to have alternating background colors but both to respond to clicks by changing their color. 我有一个自定义可绘制资源,可以在ListView中显示我的项目,实际上是两个,因为我希望结果具有交替的背景色,但是两者都可以通过更改其颜色来响应单击。 The problem is even when assigning even one of these drawables to my LinearLayout container via the layout XML, it works fine, but via Java code it doesn't. 问题是,即使通过布局XML甚至将这些可绘制对象之一分配给我的LinearLayout容器,它也能正常工作,但通过Java代码却不能。 So to be exact, this works: 因此,确切地说,这可行:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/result_white"
android:id="@+id/result"
>

but this (in my ResultAdapter which extends ArrayAdapter) doesn't: 但这(在扩展ArrayAdapter的ResultAdapter中)不:

LinearLayout result = (LinearLayout) v.findViewById(R.id.result);
result.setBackgroundColor(R.drawable.result_white);

My final objective is of course to have alternating 'result_white' and 'result_ltgray' drawables for results so the first XML solution does not really satisfy my needs. 我的最终目标当然是为结果交替使用'result_white'和'result_ltgray'可绘制对象,因此第一个XML解决方案不能真正满足我的需求。 What am I missing in the Java code please? 我在Java代码中缺少什么?

Well, assuming you are only using one-color backgrounds, you should use Colors instead since drawables can be shapes, gradients and more. 好吧,假设您仅使用一种颜色的背景,则应该使用颜色代替,因为可绘制对象可以是形状,渐变等。 Now, to actually use color, your code will look something like: 现在,要实际使用颜色,您的代码将类似于:

result.setBackgroundColor(mContext.getResources.getColor(R.color.result_white));

where mContext is the context, and you have a color (such as 0xFFFFFFFF) in your res/values/colors.xml file. 其中mContext是上下文,并且res ​​/ values / colors.xml文件中具有颜色(例如0xFFFFFFFF)。

Also take a look at Color State Lists for changing colors when pressed / selected / etc 还可以查看颜色状态列表,以在按下/选择/等时更改颜色

Thanks for your help guys, but what I needed to do is this: 感谢您的帮助,但是我需要做的是:

result.setBackgroundResource(R.drawable.result_white);

This way I could easily implement this into my ResultAdapter for alternating results reacting to clicks with changing backgrounds: 这样,我可以轻松地将其实现到我的ResultAdapter中,以使结果对背景变化的点击做出反应:

LinearLayout result = (LinearLayout) v.findViewById(R.id.result);

        if (position % 2 == 0)
            result.setBackgroundResource(R.drawable.result_white);
        else
            result.setBackgroundResource(R.drawable.result_ltgray);

确保为R导入了正确的引用(对于android drawables为android.R,对于您自己的为your_app_path.R)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM