android - Android ListView FindViewById 混淆
问题描述
我有一个带有以下适配器的 Listview
SimpleAdapter simpleAdapter
= new SimpleAdapter(NewsListActivity.this,res,R.layout.newslist_adapter,new String[]{"title","description","link"},new int[]{R.id.title,R.id.description,R.id.url});
lView.setAdapter(simpleAdapter);
其中lView是 ListView,res是 HashMap。
在 ListView 的 onItemClick 中,我能够使用下面的代码获取每个视图的描述 TextView
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
View v1 = lView.getChildAt(position - lView.getFirstVisiblePosition());
if(v1 != null){
TextView des = v1.findViewById(R.id.description);
Toast.makeText(getApplicationContext(),des.getText(),0).show(); // returns the Text at exact TextView Clicked
des.setBackgroundColor(R.color.red); //Here is the PROBLEM, It changes the Background Color of TextView I clicked on, but it ALSO changes some other TextView's background color
}
}
正如我在评论中添加的那样,Toast 消息返回 TextView 中的确切文本,但更改背景颜色也会更改 ListView 颜色中的其他一些 TextView
我似乎不明白我做错了什么。
编辑
我只发布了项目的一部分,以免把我的源代码弄乱。
这是一个 RSS 提要阅读器项目,但现在我意识到问题出在所有 ListView 上。很高兴帮助下面的链接
解决方案
好吧,经过几个月的困惑、自学的痛苦和独自行走的惩罚(无法直接向高级开发人员寻求帮助),我终于意识到我错过了什么。
问题来自 ListView 将视图重用为某种内存管理技术(出于性能目的)左右。这就是为什么在我的情况下,每当 ListView 元素的背景颜色发生更改并且视图被回收时,它都会影响使用回收视图的任何项目的背景颜色。
至于修复,这个这个链接应该有帮助
推荐阅读
- go - 使用 Golang 在数组中查找峰值
- android-studio - 如何从 Flutter 项目中将选定的 dart 文件作为主要文件运行?
- javascript - 为什么关闭窗口时componentWillUnmount不触发?
- elasticsearch - Elasticsearch - 将 API 与参数字段匹配
- environment-variables - 在 Postma 请求的正文中将环境变量转换为整数
- node.js - 不明白为什么我没有从我的树莓派 3 收到任何 rssi 数据到我的服务器
- python - 使用 jit nopython 理解 Numba TypingError
- c - 如何在 C/C++ 中的套接字编程中绑定地址?
- python - 在 Window 终端上运行“exe”Python3
- arduino - arduino nano + nrf2401 CRC_lenght=disable