由选择器设置的ListView的TextView中的文本颜色只能在“正常”状态下工作

问题描述:

我创建ListView和我自己的ListAdapter。我使用simple_list_item_2。我想改变每种状态的文字颜色。有下面的代码为dark.xml:由选择器设置的ListView的TextView中的文本颜色只能在“正常”状态下工作

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_selected="true" android:color="@color/selectedTextListColor"/> 
    <item android:state_focused="true" android:color="@color/selectedTextListColor"/> 
    <item android:state_pressed="true" android:color="@color/selectedTextListColor"/> 
    <item android:color="@color/textListColor"/> 
</selector> 

接下来它是我尝试设置该功能时的代码的一部分。我认为有一个问题。

ArrayAdapter<Element> adapter = new ArrayAdapter<Element>(instance, android.R.layout.simple_list_item_2, songsArray){ 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 

     TwoLineListItem row; 

     if (convertView == null) { 
      LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      row = (TwoLineListItem)inflater.inflate(android.R.layout.simple_list_item_2, null); 

      } else {        
      row = (TwoLineListItem)convertView; 

         } 


     Element song = songsArray[position]; 
     String data = song.text(); 

     int dashIndex = data.indexOf("-"); 

     TextView text2 = row.getText2(); 
     text2.setText(data.substring(0, dashIndex-1).trim()); 
     text2.setTextSize(12.0f); 
     text2.setPadding(10, text2.getPaddingTop(), text2.getPaddingRight(), text2.getPaddingBottom()); 

     TextView text1 = row.getText1(); 
     text1.setText(data.substring(dashIndex+1).trim());       
     text1.setTextSize(18.0f); 
     text1.setPadding(10, text1.getPaddingTop(), text1.getPaddingRight(), text1.getPaddingBottom()); 

     text1.setTextColor(getResources().getColor(R.color.dark));     

     return row; 
    } 

}; 

它仍然以这样的方式工作,文本的颜色是红色的,它在印刷机上没有改变。你能讲正确的方法吗?注意行

text1.setTextColor(getResources().getColor(R.color.dark)); 

我认为有我的错误。

text1.setTextColor(getResources().getColorStateList(R.color.dark)); 

这是我的问题。现在它运作良好。

强制在onListItemClik()之内的状态。例如:

@Override 
protected void onListItemClick(ListView l, View v, int position, long id) { 
    super.onListItemClick(l, v, position, id); 
    v.setSelected(true); 

}