在包含其他视图的布局中包装TextView

时间:2014-10-20 12:39:15

标签: android android-layout

让我们看看以下布局:

example

现在让我们做一些约束:

  • TextView必须与左侧对齐
  • 图片必须与左侧的textView文字对齐
  • CheckBox必须与右侧对齐
  • TextView可能是2行或更多(可能是很长的文本或短文本)

所以我希望它表现的方式是,只要文本足够短,剩下的空间就在图像和checkBox之间。

但是如果文本足够长,我只需要将textView拆分为2行, 因为它足够长,图像将被推动,直到它与复选框对齐。 (但它仍然与textView对齐...)

如果我使用LinearLayout,我必须使textView的宽度为0,权重为1,以便在没有空间的情况下进行分割,但是在这种情况下,图像将不会与textView的文本对齐....

所以我需要在图像和checkBox之间放置一些重量,但是它会破坏textView的重量。

相对布局不会让textView知道什么时候分割....

textView的硬编码宽度也不会很好,因为图像不会与文本对齐,不同的设备有不同的宽度。

带有drawableRight的textView也不起作用。

任何想法我怎样才能实现这种行为?

2 个答案:

答案 0 :(得分:1)

请尝试这种方式,希望这有助于您解决问题。

将图像设置为TextView

的右图
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/checkbox"
        android:gravity="left">
        <TextView
            android:id="@+id/textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawableRight="@drawable/ic_launcher" // here set you image
            android:text="android demo text"/>

    </LinearLayout>
</RelativeLayout>

答案 1 :(得分:0)

尝试这样可以帮到你,

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:baselineAligned="false"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="85"
            android:gravity="center"
            android:orientation="horizontal" >

              <TextView
            android:id="@+id/textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawableRight="@drawable/ic_launcher"
            android:text="android demo text"/>
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="15"
            android:gravity="center|right"
            android:orientation="vertical" >

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </LinearLayout>

    </LinearLayout>
相关问题