【问题标题】:How do I stop empty TextView Elements from taking up too much space in a list?如何阻止空的 TextView 元素在列表中占用太多空间?
【发布时间】:2010-12-07 01:05:52
【问题描述】:

我有一个有很多孩子的 ExpandableListView。有些孩子包含标题和描述,而有些缺少描述。我使用 SimpleExpandableListAdapter,子项的布局由 LinearLayout 中的两个 TextView 项组成。

我遇到的问题是空的描述仍然占用空间,在没有描述的项目之间造成了太多的间距。

有没有办法在适配器中动态隐藏第二个 TextView,或者设置布局以使空的 TextView 不占用任何空间?

谢谢。

【问题讨论】:

    标签: android textview expandablelistview


    【解决方案1】:

    Christian 是正确的(如果他将其发布为答案,我会简单地接受它;))。

    解决方案是创建我自己的适配器,结果证明它相当简单,尽管在设置元素的可见性时存在一些问题。基本上,您必须每次都设置它,无论您是隐藏它还是使其可见。否则你会发现不同的列表元素会在不应该显示的时候突然显示隐藏元素,反之亦然,当滚动列表时。 下面是一些示例代码:

    public class SpellListAdapter extends CursorAdapter {
        private LayoutInflater mLayoutInflater;
        private Context mContext;
        public SpellListAdapter(Context context, Cursor c) {
            super(context, c);
            mContext = context;
            mLayoutInflater = LayoutInflater.from(context); 
        }
    
        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View v = mLayoutInflater.inflate(R.layout.list_item_fave, parent, false);
            return v;
        }
    
        @Override
        public void bindView(View v, Context context, Cursor c) {
            String spell = c.getString(c.getColumnIndexOrThrow(SpellDbAdapter.KEY_SPELL));
            int fave = c.getInt(c.getColumnIndexOrThrow(SpellDbAdapter.KEY_FAVORITE));
    
            TextView Spell = (TextView) v.findViewById(R.id.text);
            if (Spell != null) {
                Spell.setText(spell);
            }
    
            //Set Fave Icon
            TextView Fave = (TextView) v.findViewById(R.id.fave_icon);
            //here's an important bit. Even though the element is set to invisible by
            //default in xml, we still have to set it every time. Then, if the 
            //spell is marked as a favorite, set the view to visible. 
            Fave.setVisibility(View.INVISIBLE);
            if (fave == 1){
                Fave.setVisibility(View.VISIBLE);
            }
        }
    
    }
    

    【讨论】:

    • 之所以每次都要设置,是因为ListView中的视图是复用的。如果列表中有 100 个元素,而屏幕上只有 10 个可见,则只会创建 10 个视图(= 性能大幅提升)。现在,当您向下滚动时,其元素已超出视图的视图将被重用并传递给 bindView 以填充现在可见的元素。
    【解决方案2】:

    尝试将可见性设置为View.GONE

    【讨论】:

    • 隐藏所有描述。有没有办法在适配器中动态设置它?
    【解决方案3】:

    似乎也设置 Fave.setHeight(0) 可以在您的适配器中解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-13
      • 2012-05-15
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 2022-07-13
      相关资源
      最近更新 更多