我需要添加添加具有复杂项目背景的ListView:顶部和底部的偶数/奇数和圆角不同。看起来像这样:
我已经通过级别列表实现了所有这些东西,但我还想做一件事。 现在底部项目位于屏幕底部附近。最好添加一些空间。
我不想向 ListView 添加底部边距,我只需要最后一项的边距。
我认为做到这一点的方法:
一种 hack – 将带有空 TextView 的页脚添加到 ListView。但是页脚是相当不稳定的东西,它们通常在notifyDataSetChanged后消失并且没有办法恢复
我要求设计师在底部背景资源中添加透明像素。不幸的是,在这种情况下,垂直居中完全被破坏。 比如有9patch是这样的:
布局如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<!-- View with background with transparent pixels on bottom -->
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
android:id="@+id/item"
android:background="@drawable/some_bgr"
android:padding="10dp"
>
<TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1"
android:text="Title"
android:layout_gravity="center"
android:textSize="18sp"
/>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Detail"
android:layout_gravity="center"
android:textSize="18sp"
/>
</LinearLayout>
<!-- Just for marking place took by view -->
<FrameLayout android:layout_width="match_parent" android:layout_height="match_parent"
android:layout_below="@id/item"
android:background="#88ff55"
/>
</RelativeLayout>
结果:
如您所见,居中不起作用。很遗憾。 (顺便说一句,如果指定这个 9patch 作为 TextView 的背景,居中效果很好。如果您知道任何文章对此进行解释,请告诉我。)
这应该可行,但由于未知的原因我仍然无法让它工作。 我不喜欢这种方式,因为我不喜欢在代码中修改尺寸。
已经有一种想象的方法——用特定的位图和边距构造一些 XML 可绘制对象。根据可绘制概念,这应该是可能的,但我找不到实现。可能有人知道吗?
还有其他想法吗?
在您的
ListView
中,设置 paddingBottom
和 clipToPadding="false"
。
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="8dp"
android:clipToPadding="false"
android:scrollbarStyle="outsideOverlay"/>
这也适用于
RecyclerView
。仅当您希望滚动条不溢出到填充区域时才使用
android:scrollbarStyle="outsideOverlay"
。将空页脚添加到您的列表中,如下所示:
TextView empty = new TextView(this);
empty.setHeight(150);
listview.addFooterView(empty);
如果你愿意,你也可以通过代码来做到这一点,例如我在这里做出反应 到EditText不同情况:
if(s.toString().length()>0)
{
contacts_lv.setClipToPadding(false);
contacts_lv.setPadding(0,0,0,270*screenDensity);
}
else
{
contacts_lv.setClipToPadding(true);
contacts_lv.setPadding(0,0,0,0);
}
钟匠的答案是最好的,而且非常聪明。您还可以创建一个空的页脚视图。
在 listView XML 代码中添加这两行:
android:transcriptMode="alwaysScroll"
android:stackFromBottom="true"
另一种解决方案可能是您制作具有一定高度的模拟视图。
在你的适配器中 getViewCount 返回 2。
在 getCount 中返回 yourData.size+1。
在 getViewType 中检查该元素是否是最后一个元素返回 2;
在 getView 中使用此类型来填充模拟视图。
我猜你只想为最后一项添加边距:
因此,您可以以这种方式执行操作,在 getview 方法中检查列表项的索引并检查它是否是最后一项,然后以编程方式向视图添加边距。