2012-12-04 55 views
0

我有一個數組的列表,並通過適配器傳遞它來填充我的列表。
其實,我想爲點擊的項目設置一些顏色。

問題是,每當我點擊第一個項目時,第一個和最後一個項目都會獲得相同的背景顏色。
列表適配器第一個和最後一個ID衝突

代碼:Test.java

//To keep track of previously clicked textview 
TextView last_clicked=null; 
ListView lv=(ListView)findViewById(R.id.my_activity_list); 

//My test array 
String[] data={"one","two","three","four","five","six"}; 

list=new ArrayList<String>(data.length); 
list.addAll(Arrays.asList(data)); 

//evolist is my custom layout 
adapter= new ArrayAdapter<String>(c,R.layout.evolist,list); 
lv.setAdapter(adapter); 
lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){ 
    public void onItemClick(AdapterView<?> ad, View v, int pos, long id){ 

         //set black for other 
         if(last_clicked!=null) 
          last_clicked.setBackgroundColor(Color.BLACK); 

         //set red color for selected item 
         TextView tv=(TextView)v; 
     //I also tried TextView tv=(TextView)v.findViewById(R.id.tvo) 
     //I tried printing tv.getId() and noticed that both first and last had same IDs 
         tv.setBackgroundColor(Color.RED); 
         last_clicked=tv; 

    } 
    }); 

佈局:evolist.xml

<?xml version="1.0" encoding="utf-8"?> 
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/tvo" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:textColor="@android:color/white" 
    android:padding="10dp" 
    android:textSize="20sp"> 
</TextView> 

我在哪裏錯了,還是隻有我得到這種錯誤? (三星galaxyŸ二重奏; 2.3.7)

+0

我不知道它爲什麼會發生,但如果它只是由於ID,嘗試給外部使用tv.setId()方法的ID。這可能會工作 –

+0

@shreya shah:你可以嘗試這個片段和評論? – everlasto

回答

1

我認爲正在發生的是,因爲viewsListView回收(當你向上滾動,從頂部消失View是用於該項目的一個出現在底部,被稱爲convertView)。

嘗試重寫getView()並將convertView的顏色設置爲黑色。

編輯:

定義一個類的成員:

String selected_item=""; 

然後將其設置爲所選擇的項目的值:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){ 
    public void onItemClick(AdapterView<?> ad, View v, int pos, long id){ 
     selected_item=((TextView) v).getText().toString(); 
     (TextView)v.setBackgroundColor(Color.RED); 
    } 
    }); 

而對於getView()

 @Override 
     public View getView(int position, View convertView, ViewGroup container) { 
      if (convertView == null) { // if it's not recycled, initialize some attributes 
       LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       convertView=li.inflate(R.layout.evolist, null); 
       } 
      if(((TextView) convertView).getText().toString().equals(selected_item)) ((TextView)convertView).setBackgroundColor(Color.RED); 
      else ((TextView)convertView).setBackgroundColor(Color.Black); 
      return convertView; 
     } 
+0

哦,從來不知道這個..btw設置背景convertview給出錯誤.. – everlasto

+0

什麼是錯誤? –

+0

Logcat顯示無法調用視圖的方法.. – everlasto

0

請更新您的代碼。

您將設置findViewById,但您已設置佈局。

檢查這一行:

ListView lv=(ListView)findViewById(R.layout.my_activity); 

評論我更新代碼之後。

+0

嘿,我打錯了,這是R.id.my_activity,謝謝..編輯問題.. – everlasto

相關問題