首页 > 解决方案 > 左视图将占用水平 LinearLayout 中的所有空间

问题描述

我有两个 TextView (tv1tv2),我希望tv2位于tv1的右侧,如下所示:

短文本

或者

长文本

(抱歉,我没有足够的声誉,无法嵌入图片:(

所以我做了这样的布局:

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

<TextView
    android:id="@+id/tv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />


<TextView
    android:id="@+id/tv2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="*" />

</LinearLayout>

如果tv1在一行之内,一切都是完美的text。但如果不止一行,tv1将占用所有空间:text

tv1 占用所有空间

我认为这可能是因为Android按照它们在布局文件中出现的顺序排列视图,所以我将根视图从LinearLayour更改为ConstraintLayout并首先制作tv2

<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<TextView
    android:id="@+id/tv2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="*"
    app:layout_constraintLeft_toRightOf="@+id/tv1"
    app:layout_constraintStart_toEndOf="@+id/tv1"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/tv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

这仍然行不通。我知道我可以使用setLayoutParams以编程方式设置tv1宽度,但除了编程还有其他方法吗?

标签: androidandroid-layout

解决方案


最后我设法通过使用padding做到了:

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingRight="12sp"
        android:text="HelloWorld"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tv2"
        android:layout_width="12sp"
        android:layout_height="wrap_content"
        android:text="*"
        app:layout_constraintRight_toRightOf="@id/tv1"
        app:layout_constraintTop_toTopOf="@id/tv1" />

</androidx.constraintlayout.widget.ConstraintLayout>

重点是使用 tv2 对 tv1 的从右到右约束,并设置 tv2 的固定尺寸宽度和 tv1 的填充右尺寸。所以 tv2 覆盖在 tv1 的顶部(和内部)。

截屏


推荐阅读