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

标签 android textview expandablelistview

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

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

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

谢谢。

最佳答案

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

}

关于android - 如何阻止空的 TextView 元素在列表中占用太多空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4372510/

相关文章:

php - 如何在 php 中将 Android 签名数据分成单独的字符串

android - 将MotionEvent转换为位置后,如何确定在可扩展 ListView 中引用了哪个列表项

android - 键盘出现时不显示 EditText

java - ExpandableListView 子级宽度

android - Textview 文本未正确显示

android - 单击其中一个按钮(不是内容区域)后如何关闭大 View 通知

android - 通过 NativeActivity NDK 访问(更快的轮询)加速度计

Android NFC 启动应用程序(使用 AAR)并读取文本

java - 让TextView点击到下一页

java - 如何在 TextView 的文本周围设置边框