【问题标题】:how do i choose convertview to reuse?我如何选择 convertview 来重用?
【发布时间】:2014-11-24 07:01:37
【问题描述】:

上下文
我想要一个包含 3 种显着不同布局的列表项列表,因此我使我的适配器根据要显示的项目类型创建适当的视图。
例如我想列出一些图像、文本和数字,每个都有一些标题。 我知道在
public View getView(int position, View convertView, ViewGroup parent)
convertView 代表重用不再可见的 listItems 视图。

问题
我如何选择convertView 或者我如何控制我在那里获得的内容?

问题来自不同的 listItems 视图,假设我的列表以图像 listItem 开头,然后是大量文本 listItems 和数字 listItems,100 个 listItems 之后是第二个图像。 我假设在向下滚动列表时,(在getView(...) 调用中)第一个不为空的convertView 是带有图像的,因为我需要一个视图来显示文本 listItem 或数字 listItem 我不能使用它。然后我猜在接下来的每个getView(...) 调用中,convertView 与之前调用中的图像 listItem 相同,因为我之前没有使用过它。

未使用的文本 listItems 和数字 listItems 竖起,滚动列表时我需要继续创建新视图,这是我想要防止的。

【问题讨论】:

    标签: android listview adapter android-adapter


    【解决方案1】:

    试试这个,

    @Override
    public View getView(final int position, View convertview, ViewGroup parent) {
        // TODO Auto-generated method stub
        final ViewHolder mHolder;
        if (convertview == null) {
            convertview = mInflater.inflate(R.layout.list_item, null);
            mHolder = new ViewHolder();
            mHolder.username_Txt = (TextView) convertview
                    .findViewById(R.id.username_Txt);
    
            convertview.setTag(mHolder);
        } else {
            mHolder = (ViewHolder) convertview.getTag();
        }
    
        try {
            mHolder.username_Txt.setText("your value");
    
    
        } catch (Exception e) {
            // TODO: handle exception
        }
    
        return convertview;
    }
    private class ViewHolder {
    
        private TextView username_Txt;
    
    }
    

    【讨论】:

    • 一点解释会有用。感谢您的回答。 +1
    【解决方案2】:

    您需要让适配器的视图回收器知道存在多个布局以及如何区分每一行的两者。只需覆盖这些方法:

    这里我已经说过 2 种不同的布局。如果您有更多使用枚举来区分它们。

    @Override
    public int getItemViewType(int position) {
        // Define a way to determine which layout to use, here it's just evens and odds.
        return position % 2;
    }
    
    @Override
    public int getViewTypeCount() {
        return 2; // Count of different layouts (Change according to your requirment)
    }
    

    将 getItemViewType() 合并到 getView() 中,如下所示:

    if (convertView == null) {
        // You can move this line into your constructor, the inflater service won't change.
        mInflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
        if(getItemViewType(position) == 0)
            convertView = mInflater.inflate(R.layout.listview_item_product_1, parent,false);
        else
            convertView = mInflater.inflate(R.layout.listview_item_product_2,parent,false);
        // etc, etc...
    

    观看 Android 的 Romain Guy 在 Google Talks 上讨论 view recycler

    【讨论】:

    • 感谢link。非常有用 +1
    猜你喜欢
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 2021-11-28
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    相关资源
    最近更新 更多