当 ListItem 被选中时,如何修改它的背景?
我有一个带有一堆 ListItem 的 ListView 。当用户选择一个项目时,我想将该 ListItem 的背景更改为图像。我怎样才能做到这一点?
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
// how do I change the ListItem background here?
}
});
I have a ListView with a bunch of ListItem's. When the user selects an item, I would like to change that ListItem's background to an image. How can I accomplish this?
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
// how do I change the ListItem background here?
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在
ListView
的适配器中进行设置。您所要做的就是在您返回的View
上使用setBackgroundResource
。让我给您一个简短的示例:请注意,我正在使用 R.drawable.the_custom_background,这意味着您必须编写一些 XML 选择器。别担心,这比听起来容易。您在
res/drawable
文件夹中创建一个名为the_custom_background.xml
的 XML 文件:再次注意,我使用的是
@drawable/the_background_color
,因此最后在res/drawable
文件夹中创建另一个名为the_background_color
的可绘制对象:我知道这看起来很混乱,但这是 Android 的方式。您还可以尝试修改
setOnItemClickListener
内的View
,但我认为这是不可取的且更难实现。You can set that in the adapter of your
ListView
. What you have to do is use thesetBackgroundResource
on theView
that you are returning. Let me give you a brief example:Notice that I'm using
R.drawable.the_custom_background
, which means that you have to write a little XML selector. Don't worry, it's easier than it sounds. You create an XML file calledthe_custom_background.xml
inside theres/drawable
folder:Notice again, I'm using
@drawable/the_background_color
, so finally create another drawable in theres/drawable
folder calledthe_background_color
:I know it seems to be very messy, but this is the Android way. You could also try to modify the
View
inside thesetOnItemClickListener
, but I think that's undesirable and harder to implement.