2012-07-12 75 views
1

我創建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)); 

我認爲有我的錯誤。

回答

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

這是我的問題。現在它運作良好。

0

強制在onListItemClik()之內的狀態。例如:

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

} 
相關問題