2012-12-04 52 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

相关问题