更改列表视图项的背景时clicke [英] change listview item background when clicke
问题描述
我有一个列表视图,我想,当我点击一排,其背景变为蓝色。我用这个code:
I have a listview and i want to when i click on a row, its background changes to blue. i use this code:
listView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
parent.getChildAt(position).setBackgroundColor(Color.BLUE);
}
});
本作品机智一些错误。当我在第一个项目点击,它变成蓝色,但项目#3和#5变为蓝色太!我不能明白为什么!我只是想唯一入选的项目将变为蓝色!
this works wit some wrong. when i click on first item, it turns to blue but item #3 and #5 changes to blue too!!! i cant understand why!! i just want only selected item turns to blue!!!
推荐答案
有关使用选择什么?他们正常工作,并提供清晰的解决方案。
What about to use selectors? They works properly and provide clean solution.
listselector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="false"
android:state_pressed="false"
android:drawable="@drawable/normal" />
<item
android:state_selected="true"
android:state_focused="false"
android:drawable="@drawable/hover"
/>
<item
android:state_selected="true"
android:state_pressed="false"
android:drawable="@drawable/hover" />
</selector>
normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid
android:color="#cccccc"
/>
</shape>
hover.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid
android:color="#dddddd"
/>
</shape>
的用法
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:listSelector="@drawable/listselector"
/>
Key属性是设置的android:listSelector =@绘制/ listselector
您的ListView
您可以在形状上也渐变属性,而不是纯色使用。而对于更多的细节,你也可以看看教程 Android的自定义的ListView 。
You can use in shape also gradient property instead of solid color. And for more details also you can look at tutorial Android Custom ListView.
这篇关于更改列表视图项的背景时clicke的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!