0

我有一个数组列表,并通过适配器将其传递给我的列表。
实际上,我想为点击的项目设置一些颜色。

问题是,每当我单击第一项时,第一项和最后一项都会获得相同的背景颜色。

代码: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>

我在哪里错了,或者只有我得到这种错误?(三星银河 y 二重奏;2.3.7)

4

2 回答 2

1

我认为正在发生的事情是因为它们views被回收了ListView(当你向上滚动时,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;
        }
于 2012-12-04T09:15:52.603 回答
0

请更新您的代码。

您将设置 findViewById 但您已经设置了布局。

检查这一行:

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

更新代码后给我评论。

于 2012-12-04T10:26:48.007 回答