【问题标题】:Centering a textview in a list using RelativeLayout vs LinearLayout使用 RelativeLayout 与 LinearLayout 在列表中居中文本视图
【发布时间】:2017-12-03 20:21:11
【问题描述】:

我有一个 RecyclerView 显示一个我想要居中的文本视图。

我的活动布局:

<?xml version="1.0" encoding="utf-8"?>
<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.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

我的 recyclerview 行布局:

<?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="wrap_content">

    <TextView
        android:id="@+id/my_textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal" />
</RelativeLayout>

activity宽度填满屏幕宽度,recyclerview匹配那个宽度,行RelativeLayout匹配recyclerview宽度,textview匹配RelativeLayout宽度。指定的重力表示将文本视图的内容水平居中。因此,文本在屏幕宽度上居中。

为什么这个逻辑不适用于 LinearLayout?将行布局的根更改为LinearLayout,重力属性不被确认。

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    使用 android:layout_gravity="center" 使 textView 相对于其他所有内容居中。 android:gravity="center" 集中子视图。更多解释见here

    【讨论】:

    • 这不起作用,因为 textview 宽度填满了屏幕。重力不以“子视图”为中心,而是以内容为中心。在这种情况下,textview 的重心是文本内容。如果我有一个会影响内容的重力视图组,那就是子视图。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多