单击列表项时,我无法更改列表项的背景

时间:2012-12-20 21:00:54

标签: android

我希望在单击列表项时更改列表项的背景,但它不起作用。

这是我的MusicAdapter内部类:

class MusicAdapter extends ArrayAdapter<String>{
        Fill fill=null;
        public MusicAdapter(){
            super(GetMusics.this,android.R.layout.simple_list_item_1,song_list);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

            row = convertView;
            if(row==null){
                LayoutInflater inflater = getLayoutInflater();
                row = inflater.inflate(R.layout.row, null);
                fill=new Fill(row);
                row.setTag(fill);
            }else{
                fill=(Fill)row.getTag();
            }
            row.setBackgroundResource(R.drawable.list_selector);
            fill.setRow(song_list.get(position));
            return row;
        }
    }

我也尝试了这个,但它再次没有用:

private AdapterView.OnItemClickListener onItemClick = new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0, View v, int arg2,
            long arg3) {
        // TODO Auto-generated method stub
        lv.getChildAt(arg2).setBackgroundResource(R.drawable.list_selector);
    }
};

这是我的list_selector.xml:

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

你有什么建议吗?

2 个答案:

答案 0 :(得分:0)

onItemClick()传递您需要更改背景的视图。只需在那里设置背景。

@Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2,
        long arg3) {
    v.setBackgroundResource(R.drawable.list_selector);
}

答案 1 :(得分:0)

您必须使用名为Selector的内容并将其设为ListSelector,请参阅此问题Android ListView Selector Color