我正在尝试在 ListView 中的第 4 项和第 5 项之间添加一些额外的空间。我有哪些选择?
我尝试在适配器的 getView() 中执行此操作,以及手动访问第四个元素并向其添加填充。
有更好的方法吗?
最佳答案
另一种方法是对第 4 个项目使用不同的布局(具有额外的填充)。它类似于您的解决方案,但可能有点“清洁”。我假设您正在扩展 ArrayAdapter。
在您的适配器中覆盖 getViewTypeCount() 方法:
@Override public int getViewTypeCount() {
return 2;
}
这样您就可以告诉您的适配器您将为您的项目使用两种不同的布局。接下来,您必须通过覆盖另一种方法来指定哪些项目属于哪种类型:
@Override public int getItemViewType(int position) {
if(position == 3) {
return 0;
} else {
return 1;
}
}
这将告诉您的适配器为列表中的第 4 个元素使用不同的 View (仅),并且不会为其他元素重用。现在对于最后一部分,覆盖 onCreateView():
@Override public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
if(position == 3) {
convertView = inflater.inflate(R.layout.your_layout_with_padding, parent, false);
} else {
convertView = inflater.inflate(R.layout.your_regular_item_padding, parent, false);
}
//TODO this is the place to initialize your view holder
} else {
//TODO this is the place to restore your view holder
}
//TODO setup your view here
return convertView;
}
对于位置 == 3 的项目(列表中的第 4 项),getView() 方法的 convertView 参数将为 null,因为这是该类型的第一个(也是唯一一个)项目1 在列表中。因此,您可以膨胀一个不同的布局,其中包括该项目的填充。
关于android - 如何在 ListView 中间添加一些空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27367461/