【问题标题】:Center text items in ListView在 ListView 中居中文本项
【发布时间】:2013-04-23 11:39:50
【问题描述】:

如何在Layout 中水平居中对齐ListView 的文本项?
老实说,在提出这样一个基本问题之前,我至少搜索了一个小时。

谢谢。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:hint="Remind..." />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:baselineAligned="false"
        android:orientation="horizontal" >

        <ListView
            android:id="@+id/listviewTimeInterval"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:scrollbars="none" />

         <-- . . . --/>
         <-- more lists of the same kind--/>
         <-- . . .--/>

    </LinearLayout>

</LinearLayout>

【问题讨论】:

  • 不应该在自定义项 XML 中设置 TextViewsgravity 吗?

标签: android android-layout android-widget


【解决方案1】:

您需要为您的列表视图项创建自己的布局,类似于这样

例子:

文本中心.xml:

<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center" >
    <TextView
        android:id="@id/textItem"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

然后,在您的代码中,您必须这样做

ArrayAdapter<String> ad = new ArrayAdapter<String>(this, R.layout.textcenter, R.id.textItem, functions);
listView.setAdapter(ad);

【讨论】:

  • 您的答案(如果有效)。但我相信 OP 已经在使用某种自定义的ListView。它的 ID 为listviewTimeInterval
  • ListView 本身不控制文本在其中的显示方式吗?为什么要使用单独的布局?
  • 好吧,我误解了布局的作用,认为它们只需要活动。然后我意识到 ListView 实际上是许多视图的列表,每个视图都有特定的布局。
  • 你应该在 TextView 中将 android:layout_width="fill_parent" 更改为 android:layout_width="wrap_content"
【解决方案2】:

如果 LisView 本身定义为 android:layout_width="wrap_content" 这没有任何意义,因为这个参数应该只影响 ListView 的位置,而不是它的元素。

无论如何,将列表的宽度更改为 match_parent 允许将项目的 (layout_)gravity 属性居中。

【讨论】:

  • 谢谢!几个小时以来一直试图将列表视图居中。
【解决方案3】:

在自定义 ListView xml 文件的 TextView 布局中使用 android:gravity="center" 。这样就可以了。

【讨论】:

  • 这对于答案来说有点短,可以改为评论。您是否阅读过关于如何回答 StackOverflow 问题的 guide
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-03
  • 1970-01-01
  • 2012-01-14
  • 2021-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多