【问题标题】:TextView dynamic width with a view at the endTextView 动态宽度,末尾有一个视图
【发布时间】:2019-12-21 10:24:02
【问题描述】:

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

但问题是,如果文字太长,ImageView 会从屏幕中消失,如下所示:

但应该是这样的:

我怎样才能仅通过 XML 获得它?我知道以编程方式可以实现,但我想要一个 XML 解决方案。

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

【问题讨论】:

  • 显示你的布局 xml。

标签: android android-layout


【解决方案1】:

你可以试试这个,这里的关键是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>

【讨论】:

    【解决方案2】:

    你可以改变 layoutDirection 来固定布局的方向,例如

    <?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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-31
      相关资源
      最近更新 更多