我有一个数组的列表,并通过适配器传递它来填充我的列表。
其实,我想为点击的项目设置一些颜色。
问题是,每当我点击第一个项目时,第一个和最后一个项目都会获得相同的背景颜色。
列表适配器第一个和最后一个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)
我不知道它为什么会发生,但如果它只是由于ID,尝试给外部使用tv.setId()方法的ID。这可能会工作 –
@shreya shah:你可以尝试这个片段和评论? – everlasto