2011-06-16 62 views
0

我有一个自定义列表视图,我正在使用自定义listadapter来显示该列表。在我的自定义listadapter中,我试图根据对象内的值动态设置每个项目的颜色。然而,无论何时我尝试这样做,项目都会变淡,而不是获取它们设置的颜色。我在项目中应用了一些样式,但是当我删除它们的效果时,它仍然不起作用。这是我的代码来改变每个项目的背景色:为什么我无法动态设置自定义Listview项目的背景?

private class stationAdapter extends ArrayAdapter<Station>{ 
    private ArrayList<Station> stations; 

    public stationAdapter(Context context, int textViewResourceId, ArrayList<Station> stations) { 
     super(context, textViewResourceId, stations); 
     this.stations = stations; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     View v = convertView; 
     if (v == null) { 
      LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      v = vi.inflate(R.layout.row, null); 
     } 
     Station temp = stations.get(position); 
     if (temp != null) { 
      TextView stationName = (TextView) v.findViewById(R.id.stationname); 
      TextView serviced = (TextView) v.findViewById(R.id.inservice); 

      try{ 
       if(temp.getLine().equals("red")){ 
        v.setBackgroundColor(R.color.red); 

       } 
       else{ 
        v.setBackgroundColor(R.color.green); 
       } 
      }catch(Exception e){ 
       Log.d(TAG, "Null pointer"); 
      } 
      if (stationName != null) { 
       stationName.setText("Station: "+temp.getName());       } 
      if(serviced != null){ 
       serviced.setText("In Service: "+ temp.getInServive()); 
      } 
     } 
     return v; 
    } 

} 

如果有人能指出我在做什么错了,我真的很感激它。

回答

2

就像Darko提到的,你试图设置一种颜色,但是使用资源ID来代替。随着中说,使用列表项的背景纯色是一大禁忌,你一定要使用一个选择:在您的绘图资源文件夹

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_focused="false" android:state_pressed="false" android:state_selected="false" 
     android:state_checked="false" android:state_enabled="true" android:state_checkable="false" 
     android:drawable="@color/red" /> 
</selector> 

将在一个list_red_background.xml和使用setBackgroundResource()代替。

+0

那么使用这个drawable来设置颜色,这也将解决我的新突出问题?谢谢 – Hugs 2011-06-16 14:50:20

+0

是的,这会解决它。这个选择器说的是:只对默认状态(未按下,未选中等)应用红色,对于其他任何情况,使用默认颜色/可绘制。 – dmon 2011-06-16 14:51:01

3

你不能使用setBackgroundColor,然后引用的资源。如果你想使用setBackgroundColor(),您需要使用Color类,如:如果你想设置一个资源

setBackgroundColor(Color.BLACK); 

相反(R.drawable,R.color等......),你需要做的像

v.setBackgroundResource(R.color.black); 

编辑:

缓存颜色提示是,如果项目开始变得灰暗,而滚动列表中所需要的。如果要将自定义背景添加到项目和列表,则需要将其设置为透明颜色。

+0

完美谢谢:) – Hugs 2011-06-16 14:31:38

+0

将它标记为已回答,然后请让人们知道它已解决。 – DArkO 2011-06-16 14:33:26

+0

还有一个问题,如果你不介意。我有一个drawable,每当一个项目的重点项目突出显示将是蓝色的。但没有什么突出显示了。我这样做的方式是在我的row.xml类中,并做了。现在还有另一种方法可以做到这一点吗?谢谢 – Hugs 2011-06-16 14:37:52

相关问题