我有一个包含很多子项的 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/