开发者

Using ColorStateList in Android Java code

I have a list with items, and 2 colorliststates, one for the odds, one for the evens. basically, it ressembles this :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false" android:color="#fff" />
    <item android:state_pressed="true" an开发者_JS百科droid:color="#999" />
</selector>

How can I use apply the colorliststate to the items? in the layout, there is no notion of odd or even, so i can't. In the java code, I can't find a way of using the colorliststate once i load it :

getContext().getResources().getColorStateList(R.color.list_even);

Any idea?


You can use:

// you must place your file in the res/color folder
widget.setTextColor(getContext().getResources().getColor(R.color.list_even));

Or just put it in the textColor attribute if you are using XML:

<SomWidget
    android:textColor="@color/list_even"/>


First define two different selector drawables. You can refer in the drawable xml to a color.xml or enter directly the color value. To use the color.xml is more fancy.

Second I guess you have ListAdapter implementation. So in your getView(..) implementation you can set different background drawables for odd and even items. I guess you want to modify the background and not the text color because you posted an example referring to a pressed state.

Expressed in code, without having eclipse here and totally correct Syntax in mind:

if (position % 2 == 0) {
  view.setBackGroundDrawable(R.drawable.selector1);
}
else {
  view.setBackgroundDrawable(R.drawable.selector2);
}

Does my example match what you want?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜