带有TypedArray Id Color的setBackgroundColor

时间:2015-05-07 14:08:58

标签: android colors resources adapter

在View类型的对象上使用setBackgroundColor()方法时遇到问题。 我想要使​​用的颜色在我的文件strings.xml

中的数组中声明
<array name="nav_news_colors">
        <item>@color/nav_1</item>
        <item>@color/nav_2</item>
        <item>@color/nav_3</item>
</array>

colors.xml

<color name="nav_1">#919fa1</color>
<color name="nav_2">#ffa2a6</color>
<color name="nav_3">#a28bc3</color>

然后,在我的ActivityMain.java

navMenuNewsColors = getResources()
                .obtainTypedArray(R.array.nav_news_colors);


navNewsItems = new ArrayList<NavNewsItem>();

navNewsItems.add(new NavNewsItem(navTitles[0], navColors.getResourceId(0, -1)));
navNewsItems.add(new NavNewsItem(navTitles[1], navColors.getResourceId(1, -1)));
navNewsItems.add(new NavNewsItem(navTitles[2], navColors.getResourceId(2, -1)));

public class NavNewsItem {
	
	private String title;
	private int color;
	
	public NavNewsItem(){}

	public NavNewsItem(String title, int color){
		this.title = title;
		this.color = color;
	}
	
	public String getTitle(){
		return this.title;
	}
	
	public int getColor(){
		return this.color;
	}
	
	public void setTitle(String title){
		this.title = title;
	}
	
	public void setColor(int color){
		this.color = color;
	}
}

但是我不能在setBackgroundColor的适配器中使用它:

View imgColor = (View) convertView.findViewById(R.id.v_color);
imgColor.setBackgroundColor(navDrawerItems.get(position).getColor());

1 个答案:

答案 0 :(得分:2)

您只需将navColors.getResourceId(0, -1)更改为navColors.getColor(index, defValue),然后您就可以同时使用setBackgoundColorsetTextColor