如何在可展开列表视图的某些子视图上动态显示图像

时间:2014-11-20 14:03:42

标签: android listview

我试图找出如何仅在可扩展列表视图中的某些子视图上显示图像。我需要根据组和子索引进行设置。我尝试通过索引这样做:

public View getChildView(final int groupPosition, final int childPosition,
        boolean isLastChild, View convertView, ViewGroup parent) {
    final String laptop = (String) getChild(groupPosition, childPosition);
    LayoutInflater inflater = context.getLayoutInflater();

    if (convertView == null) {
        convertView = inflater.inflate(R.layout.child_item, null);
    }

    ImageView email = (ImageView) convertView.findViewById(R.id.email);
    //this shows the email icon where applicable
    if (groupPosition == 0 && childPosition == 0 ){
        email.setVisibility(View.GONE);
    }
    if (groupPosition == 2 && childPosition == 0 ){
        email.setVisibility(View.GONE);
    }

    item.setText(Html.fromHtml(laptop));
    return convertView;
}

但是当你开始向下滚动时,由于回收的工作方式,它开始将不同的设置为GONE。我该如何解决这个问题呢?

1 个答案:

答案 0 :(得分:1)

您不需要从外观中回收视图。如果你不需要,不要这样做。 (所有文档都使它听起来像一个要求,所有的例子都使用它,但它不是必需的。它只是“良好的做法”,但是当“良好实践”需要10倍时,只要完成工作就应该采取,它真的不是一个好的做法吗?)

回收背后的概念与滚动很长的项目列表有关。如果您的列表只包含几个项目,则无需执行此操作。

如果您最终需要,这将修复您的代码:

ImageView email = (ImageView) convertView.findViewById(R.id.email);
//this shows the email icon where applicable
if (groupPosition == 0 && childPosition == 0 ){
    email.setVisibility(View.GONE);
} else
if (groupPosition == 2 && childPosition == 0 ){
    email.setVisibility(View.GONE);
} else {
    email.setVisibility(View.VISIBLE);
}

如果您不想回收视图,只需忽略此convertView

public View getChildView(final int groupPosition, final int childPosition,
        boolean isLastChild, View convertView, ViewGroup parent) {
    final String laptop = (String) getChild(groupPosition, childPosition);
    LayoutInflater inflater = context.getLayoutInflater();

    View newView = inflater.inflate(R.layout.child_item, null);

    ImageView email = (ImageView) newView.findViewById(R.id.email);
    //this shows the email icon where applicable
    if (groupPosition == 0 && childPosition == 0 ){
        email.setVisibility(View.GONE);
    } else
    if (groupPosition == 2 && childPosition == 0 ){
        email.setVisibility(View.GONE);
    } else {
        email.setVisibility(View.VISIBLE);
    }

    item.setText(Html.fromHtml(laptop));
    return newView;
}