【问题标题】:Android ListView Adapter adding viewsAndroid ListView Adapter 添加视图
【发布时间】:2016-07-15 02:04:11
【问题描述】:

我正在尝试更改 ListView 中某些项目的颜色。它因 NullPointerException 而崩溃,我不完全确定为什么,我认为这是因为适配器尚未创建视图/将视图添加到 ListView,因此它试图检索不在数组中的项目。只要列表上至少有 1 项,我就可以完美地添加彩色项目。我该如何解决这个问题?

        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++;
    }

【问题讨论】:

    标签: android listview android-adapter


    【解决方案1】:

    不要通过索引接触到孩子来进行这样的 UI 更改。这是在自找麻烦:

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

    相反,根据一些逻辑来更改适配器的 getView() 中的项目视图,这些逻辑确定哪些单个项目应该具有什么背景颜色。

    【讨论】:

      【解决方案2】:

      你应该把这种逻辑放在你的 Adapter 的 getView 方法中。 在那里,您可以根据其值修改项目的背景颜色。

      关于这个话题有很多话题。 例如看看这里:How can I change the background color of list items based on the data being displayed in each item?

      【讨论】:

        猜你喜欢
        • 2015-07-29
        • 2014-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-28
        • 2011-09-05
        • 1970-01-01
        相关资源
        最近更新 更多