【问题标题】:Why does this textView expands to the left beyond its parent borders?为什么这个 textView 向左扩展超出其父边界?
【发布时间】:2016-02-27 01:33:29
【问题描述】:

我有一个 TextView 和一个 ImageView,它们之间有一个空格。我希望 ImageView 位于 TextView 的右侧,并且 TextView 动态地更改其大小。我设法做到了,但是如果文本太长,textView 会向左扩展超出其父边界。为什么会这样?我能做些什么来解决它?

<LinearLayout
    android:layout_height="match_parent"
    android:layout_width="wrap_content"
    android:orientation="horizontal"
    android:gravity="right|center_vertical">

    <TextView
        android:id="@+id/received"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:padding="5dip"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:background="@drawable/received_style"
        android:text="dsssssajhhhhhhhhhhhhhhhhhhhoooooooooohsssssssssdhsfsd"
        />

    <Space
        android:layout_width="5dp"
        android:layout_height="0dp"
        />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:src="@drawable/edit" />
</LinearLayout>

【问题讨论】:

  • 发现错误! LinearLayout 的 layout_width 是“wrap_content”,而不是“match_parent”。现在代码和我电脑上的一样。

标签: android android-layout android-linearlayout


【解决方案1】:

为 TextView 设置权重。

    android:layout_weight="1"

【讨论】:

    【解决方案2】:

    LinearLayout 为每个孩子提供至少与其要求一样多的空间。

    您可以改用RelativeLayout,将ImageView 与父右侧对齐,TextViewImageView 对齐。

    【讨论】:

    • 我不希望 ImageView 在父右侧对齐,而是动态定位在 textView 的右侧。
    【解决方案3】:

    你可以试试这样的。

    <RelativeLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        xmlns:android="http://schemas.android.com/apk/res/android">
    
        <TextView
            android:id="@+id/received"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:padding="5dip"
        android:layout_toLeftOf="@+id/space"
            android:text="dsssssajhhhhhhhhhhhhhhhhhhhoooooooooohsssssssssdhsfsd"
            />
    
        <Space
            android:id="@+id/space"
            android:layout_width="5dp"
            android:layout_height="0dp"
            android:layout_toLeftOf="@+id/imageView"
            />
    
        <ImageView
            android:id="@+id/imageView"
            android:layout_width="30dp"
            android:layout_alignParentRight="true"
            android:layout_height="30dp"
            android:src="@drawable/edit" />
    </RelativeLayout>
    

    希望能帮到你!

    【讨论】:

      猜你喜欢
      • 2015-04-25
      • 2021-08-19
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 2012-07-24
      • 1970-01-01
      • 2012-06-08
      • 2011-02-19
      相关资源
      最近更新 更多