Android ListView Adapter 添加视图

Android ListView Adapter adding views

我正在尝试更改 ListView 中某些项目的颜色。它因 NullPointerException 而崩溃,我不确定为什么,我认为这是因为适配器没有 created/added ListView 的视图,所以它试图检索不在数组中的项目。只要列表中至少有一项,我就可以完美地添加彩色项目。我该如何解决?

        int index = 0;
    for(ItemEntry i: tentry) {
        adapter.add(i.Name); // Adding to Adapter
        adapter.notifyDataSetChanged(); // Telling it I've done so
        long time = TimeUnit.MILLISECONDS.toDays(i.Date.getTime() - System.currentTimeMillis());
        ListView stuff = (ListView) this.findViewById(R.id.contentsList);
        if( time < 0 ) {
            stuff.getChildAt(index).setBackgroundColor(Color.RED); // Null exception
        } else if( time < 1 ) {
            stuff.getChildAt(index).setBackgroundColor(Color.RED); // Null exception
        } else if( time < 2 ) {
            stuff.getChildAt(index).setBackgroundColor(Color.YELLOW); // Null exception
        }
        index++;
    }

不要通过索引进入 children 进行这样的 UI 更改。找麻烦了:

stuff.getChildAt(index).setBackgroundColor(Color.RED); // Null exception

相反,根据确定哪些个别项目应具有何种背景颜色的逻辑,在适配器的 getView() 中更改项目视图。

您应该将这种逻辑放在适配器的 getView 方法中。 在那里你可以根据它的值修改项目的背景颜色。

关于此主题的讨论帖很多。 例如看这里:How can I change the background color of list items based on the data being displayed in each item?