【问题标题】:How to create a different view for the last item of an ArrayAdapter?如何为 ArrayAdapter 的最后一项创建不同的视图?
【发布时间】:2011-02-07 17:34:58
【问题描述】:

我正在从 URL 中检索项目列表,并使用自定义的 ArrayAdapter 在 ListView 中显示它们。我最多显示 25 个结果,但最多从 URL 中检索 26 个,因为如果超过 25 个,我想显示“下一个”链接。我试图找出一种方法让视图中的最后一个项目只显示下一个链接,而不是其他项目显示的图像和两个 TextView。向下滚动,所有项目都以它们应该的方式显示,但最后一个项目仍然看起来像其他项目。向上滚动时,每五个项目都是空白的(可以看出它仍然存在,因为有分隔线)。

getView 内部:

if (position + 1 == limit) { // Limit = 26, corresponding position is 25
    Log.e("Last Item", String.valueOf(position));
    // Gone
    image.setVisibility(8);
    text.setVisibility(8);

    // Visible
    next.setVisibility(0);
} else {
    if (item != null) {

        Log.e("Other item", String.valueOf(position));
        if (top_text != null) {
            top_text.setText(item.getItemTitle(), BufferType.SPANNABLE);
        }
        if(bottom_text != null){
            bottom_text.setText(item.getItemDescription());
        }
    }
}
return view;

在 ddms 中,它只为最后一项打印“Last Item”标签,为其余项目打印“Other Item”标签,但不会根据 if-else 更改这些项目。在 XML 中,next 设置为消失,因此不需要在 else 中更改。当我删除 if-else 并仅在 else 中保留代码时,列表正常运行,但我需要下一个链接。关于奇怪行为的原因有什么想法吗?如果您需要查看任何其他代码或需要澄清正在发生的事情,请告诉我。

【问题讨论】:

    标签: android listview android-arrayadapter


    【解决方案1】:

    请发布getView的完整代码。 您返回视图;但是什么是视图,是convertView还是从xml膨胀?

    这是我如何为最后一项获得不同视图的方式: 1.创建2个布局,第一个用于普通项目,第二个用于最后一个项目 2. in getView(int position, View convertView, ViewGroup parent)

    View view = convertView;
    if (view == null) {
    LayoutInflater vi = (LayoutInflater) mContext
                            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = vi.inflate(R.layout.xxx, null);
    } else {
        //check if view is not layout we need (based on position), we need inflate from xml
    }
    
    //set text ...
    

    【讨论】:

    • 视图是转换视图。我从没想过只使用不同的布局,但它成功了。谢谢!
    猜你喜欢
    • 2014-03-23
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    相关资源
    最近更新 更多