如何阻止空TextView元素占用列表中的太多空间?

时间:2010-12-07 01:05:52

标签: android textview expandablelistview

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

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

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

感谢。

3 个答案:

答案 0 :(得分:4)

克里斯蒂安是正确的(如果他把它作为答案张贴,我会简单地接受它;))。

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

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);
        }
    }

}

答案 1 :(得分:1)

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

答案 2 :(得分:0)

似乎也设置了Fave.setHeight(0)可以在你的适配器中做到这一点。