具有末尾视图的TextView动态宽度

时间:2019-12-20 18:45:34

标签: android android-layout

我有两个元素,一个TextView和一个ImageViewImageView将在TextView的末尾。 TextView的宽度将根据文本而变化,ImageView也将跟随TextView的结尾。像这样:

enter image description here

但是问题是,如果文本太长,ImageView就会从屏幕上消失,就像这样:

enter image description here

但是应该像这样:

enter image description here

如何仅通过XML获得此信息?我以编程方式知道可以实现,但是我想要一个XML解决方案。

注意:ImageView可以是Button,所以我不能像解决方案那样使用drawableEnd

2 个答案:

答案 0 :(得分:2)

您可以尝试一下,这里的密钥是app:layout_constrainedWidth="true"

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
    android:id="@+id/left"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="lefttttttttttttttttttttttttttttttttttttttttttttttttt"
    app:layout_constrainedWidth="true"
    app:layout_constraintHorizontal_chainStyle="packed"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toStartOf="@id/right"
    app:layout_constraintTop_toTopOf="parent"/>
 <ImageView
    android:id="@+id/right"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:src="@mipmap/ic_launcher"
    app:layout_constraintStart_toEndOf="@id/left"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="@id/left"
    />
</android.support.constraint.ConstraintLayout>

答案 1 :(得分:2)

您可以更改layoutDirection以固定布局的方向,例如 img1 img2

<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
    tools:context=".MainActivity"
    android:layoutDirection="rtl"
    android:gravity="left">
    <Button
        android:layout_width="100dp"
        android:layout_height="40dp"
        app:layout_constraintStart_toEndOf="@id/left"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@id/left"
        android:text="abc"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="How can I get this only by XML? I know programatically it can be achieved, but I want a XML solution."/>

</LinearLayout>