比较字符串时选择了ListView的错误项目

时间:2016-03-25 20:08:27

标签: android listview

适配器:

public class CategoryAdapter extends ArrayAdapter<Category> {
    public CategoryAdapter(Context context, ArrayList<Category> categories){
        super(context, 0, categories);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Category category = getItem(position);

        if(convertView==null){
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_game_choose_category, parent, false);
        }

        TextView categoryName = (TextView) convertView.findViewById(R.id.category);
        TextView categorySubtext = (TextView) convertView.findViewById(R.id.categorySub);
        TextView categoryQuestionsCount = (TextView) convertView.findViewById(R.id.categoryQuestionsCount);

        categoryName.setText(category.categoryName); // Populate
        categorySubtext.setText(category.categorySubtext);
        categoryQuestionsCount.setText(category.categoryQuestionsCount);


        return convertView;
    }
}

型号:

public class Category {
   public Category(String categoryName,
                    String categoryId,
                    String categoryParentId,
                    String categoryQuestionsCount,
                    String categorySubtext) {
        this.categoryName = categoryName;
        this.categoryId = categoryId;
        this.categoryParentId = categoryParentId;
        this.categoryQuestionsCount = categoryQuestionsCount;
        this.categorySubtext = categorySubtext;
    }
}

我想要隐藏空的TextViews,所以在Adapter中的getView方法中我写了类似的内容:

if(category.categorySubtext.equals("")) { categorySubtext.setVisibility(View.GONE); }

但突然间,即使是那些有&#34; categorySubtext&#34;填写,被这个条款召唤!在滚动浏览ListView之后,所有项目都具有可见性:已消失。

我也尝试过调用category.categorySubtext.isEmpty()category.categorySubtext.trim().equalsIgnoreCase() - 每当我遇到相同的行为时。

所有建议都赞赏!

2 个答案:

答案 0 :(得分:2)

视图将重复用于ListView的不同行/项,并且您永远不会将它们设置为可见。

使用类似的东西:

categorySubtext.setVisibility(
         category.categorySubtext.isEmpty() ? View.GONE : View.VISIBLE
     );

答案 1 :(得分:1)

尝试添加else语句,将可见性更改为visible