ListView:为什么第一次没有背景改变?

时间:2017-01-30 17:50:12

标签: android android-layout listview

我需要一种方法来改变所选项目的背景颜色。以下代码仅在我第二次单击某个项目时更改背景颜色(蓝色)。因此,当我第一次点击某个项目时,它不起作用。

final SongAdapter songAdt = new SongAdapter(getApplicationContext(), songList);
lv.setAdapter(songAdt);

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.i(TAG, " executed");
            view.setBackgroundColor(Color.BLUE);
        }
    }
);

我刚刚检查过(通过使用Log.i函数)代码执行了2次,但只是第二次更改了背景。为什么?

3 个答案:

答案 0 :(得分:1)

试试这个:

private int prevPosition=-1;

和您的onItemClick使用:

lv.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> adapter, View view,
            int position, long arg3) {

        for (int i = 0; i < adapter.getChildCount(); i++) {
            if (i == position) {   

                if(position!=prevPosition){
                   //set your selected color                    
                   adapter.getChildAt(i).setBackgroundColor(Color.BLUE);
                    prevPosition=position;

                }else{
                    adapter.getChildAt(i).setBackgroundColor(Color.BLACK);
                    prevPosition=-1;
                   }

               }else{
                  //set your normal color   
                  adapter.getChildAt(i).setBackgroundColor(Color.BLACK);

               }

            }
    }

});

选项2

您可以为listview

使用drawable选择器

res/drawable文件夹

background.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" 
    android:drawable="@drawable/pressed" />
<item  android:state_focused="false" 
    android:drawable="@drawable/normal" />
</selector>

pressed.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
<solid android:color="#000000"/>  // set your selected color   
<padding android:left="5dp"
         android:top="5dp"
         android:right="5dp"
         android:bottom="5dp"/> 
</shape>

normal.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
<solid android:color="#FFFFFF"/>    

<padding android:left="5dp"
         android:top="5dp"
         android:right="5dp"
         android:bottom="5dp"/> 
</shape>

现在在xml中的listview中使用它:

android:listSelector="@drawable/background" 

答案 1 :(得分:0)

在listview中,我们有属性android:listSelector =&#34; @ color / sky&#34;在xml中使用它。这将改变所选的项目背景。希望这对你有用。

答案 2 :(得分:0)

删除行

view.setBackgroundColor(Color.BLUE);

并添加此行并查看是否正常工作

parent.getChildAt(position).setBackgroundColor(getResources().getColor(R.color.list_blue_colour));

我尚未测试过,请分享工作,如果不工作,请按照此回答over here

相关问题