【问题标题】:ListView - Center Cell Views Horizontally w/o ListView Height Wrap_ContentListView - 水平居中单元格视图,不带 ListView 高度 Wrap_Content
【发布时间】:2015-04-21 11:47:21
【问题描述】:

我目前在使用 Android 的 ListView 时遇到一些格式问题。在查看了关于 SO 的几个问题后,我没有找到任何合适的解决方案。

我有一个 ListView(用于导航),包括一个或多个视图(实际导航项)。我想要实现的是 - ListView 占用了整个垂直空间(高度设置为 match_parent),并且单元格在此 ListView 中垂直居中。

仅将 ListView 的重力设置为 center_vertical 并不能解决问题。如果我将 ListView 包装在另一个视图(已将重力设置为 center_vertical)并将 ListView 的高度更改为 wrap_content,我目前只能实现这种外观。但这似乎不是完美的解决方案,因为生成的测量操作(适配器的 getView 方法在同一位置被多次调用)会对性能产生影响,即使为导航项应用了适当的持有人概念也是如此。这个问题有解决办法吗?

ListView(重力不起作用):

<ListView android:id="@+id/lvNavigation"
        android:layout_width="@dimen/navWidth"
        android:layout_height="match_parent"
        android:gravity="center_vertical" />

带有解决方法的 ListView(性能不佳):

<LinearLayout android:layout_width="@dimen/navWidth"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center_vertical">

    <ListView android:id="@+id/lvNavigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

</LinearLayout>

导航项:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_height="wrap_content"
        android:layout_weight="match_parent"
        android:gravity="center_vertical"
        android:orientation="vertical"
        android:paddingLeft="@dimen/horizontalMargin"
        android:paddingRight="@dimen/horizontalMargin">

    ...

</LinearLayout>

【问题讨论】:

  • 发布您的列表以及列表项布局。
  • 我已经添加了相关的布局部分。
  • 如果性能不佳,请使用相对布局并将 centerVertical=true 设置为 listview。
  • 移除 xml 声明中的 android:gravity="center_vertical"。 就够了
  • @Harry:我尝试了您的解决方案,但由于测量原因,getView 仍然被多次调用(ListView 的高度设置为 wrap_content)。

标签: android performance listview gravity


【解决方案1】:

Listview 用于此目的可能是一件坏事。我认为您应该做的是使用带有自定义 Layout Manager 的回收站视图

特别是您可能想要覆盖onLayoutChildren

我进行了快速搜索,但找不到可以为您执行此操作的库。

或者,如果您有可以预测高度的元素,则可以add a header view 为空白并设置高度,以便列表项居中显示。

类似

ListView lv = getListView();
LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.header, lv, false);
header.setLayoutParams(new AbsListView.LayoutParams(<width>, <height>));
lv.addHeaderView(header, null, false);

【讨论】:

  • 我会看看 RecyclerView。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多