【问题标题】:Android ListView FindViewById confusionAndroid ListView FindViewById 混淆
【发布时间】:2021-03-23 14:04:08
【问题描述】:

我有一个带有以下适配器的 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 中,我可以使用下面的代码获取每个 View 的 Description 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 上。很高兴通过下面的链接提供帮助

Android ListView getChild() not working properly

【问题讨论】:

  • 请贴出ListView的行项布局
  • 这些项目是从一些 Rss 提要的 RSS 新闻动态生成的。 HashMap 中的普通键值对
  • 编辑 我意识到问题出在所有 ListView 上。 stackoverflow.com/questions/65266929/…
  • 我的意思是分享你从哪个布局得到R.id.description你能分享吗?可能来自R.layout.newslist_adapter

标签: android android-listview listviewitem findviewbyid


【解决方案1】:

好的,经过数月的困惑、自学的痛苦和独自行走的惩罚(无法直接向高级开发人员寻求帮助),我终于意识到我错过了什么。

问题来自 ListView 重用视图作为某种内存管理技术(出于性能目的)左右。这就是为什么在我的情况下,每当 ListView 元素的背景颜色发生更改并且视图被回收时,它都会影响使用回收视图的任何项目的背景颜色。

至于修复,这个this 链接应该会有所帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多