Android LinearLayout 中心 TextView 等等

标签 android android-layout

我有一个带有三个 TextViews foo、bar 和 baz 的 LinearLayout。 foo 应该在左边,bar 居中,baz 在右边。这是我到目前为止得到的:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="foo" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="bar" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="baz" />
</LinearLayout>

我遇到的问题是,当 foo 和 baz 的大小相同时,bar 仅居中。此外,baz 的文本可能会在程序执行期间发生变化,从而使 bar 跳来跳去以保持与 foo 和 baz 的距离相等。

我希望 bar 总是在 LinearLayout 中居中,无论 foo 和 baz 的(可能变化的)大小如何。我该如何存档?

最佳答案

这应该是您要查找的内容。它会将中间的 TextView 保持在布局的中间,而不管左右 TextView 的值是什么(注意我已经改变了你的文本长度foo 和 baz 值)。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="left"
        android:text="asdfasdfasdf" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="bar" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="right"
        android:text="dfdfdf" />
</LinearLayout>

关于Android LinearLayout 中心 TextView 等等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35587283/

相关文章:

java - 应用程序停止工作

android - 在relativeLayout中依次添加几个textView(可变宽度)

android - Fragment 中 onCreateView 和 onViewCreated 的区别

android - android中的 ListView 正常和悬停背景样式

android - TextView 不适合 ScrollView

android - 升级到 SDK 2.3 - 现在没有仿真器具有连接性

android - 应用程序的生命周期 : How to do some clean jobs when the process is terminated?

java - Android 在没有 new mClass() 的情况下将类创建到单独的文件中...?

android - API 驱动的应用程序 - 嵌套 fragment - 在哪里进行 API 调用? onStart 与 onResume 上的 onCreateView

android - Android Studio 在哪里保存 ProGuard 映射文件?