Android宽度根据另一个宽度

时间:2013-11-14 14:11:39

标签: android relativelayout

以下图片可以显示我想要的最终结果。

enter image description here

答:如果我输入小值,图像(包含矩形)就可以了。

B:如果我输入较大的值,而不是重新调整图像,它将保持相同的宽度。

C:我想要的最终结果。矩形将自己调整为textview值的长度。

我想知道是否有可能只在XML中获得结果?我目前的代码如下:

<ImageView 
    android:id="@+id/image"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:layout_marginRight="0dp"
    android:layout_marginTop="0dp"
    android:background="@drawable/bg_sendsuccess"
/>

<TextView 
    android:id="@+id/numberId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/numberId"
    android:textSize="22sp"
    android:textColor="#fff"
    android:textStyle="bold"
    android:layout_marginTop="3dp"
    android:layout_marginRight="5dp"
    android:layout_alignParentRight="true"
/>

2 个答案:

答案 0 :(得分:1)

如果您使用的背景只是一个简单的矩形,您可以从xml创建该背景图像并将其设置为TextView的背景。

drawable文件夹中创建名为res的文件夹。在drawable文件夹内创建一个xml文件(形状)(让我们称之为text_background.xml

text_background.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<!-- Rounded Corner Settings -->
<corners
    android:bottomLeftRadius="8dp"
    android:bottomRightRadius="8dp"
    android:topLeftRadius="0dp"
    android:topRightRadius="0dp" />

<!-- Rectangle Solid Color Settings -->
<solid android:color="#ffffff" />

<!-- Rectangle Stroke Settings -->
<stroke
    android:width="1dp"
    android:color="#000000" />

</shape>

然后在layout xml中将此形状添加到TextView作为background

<TextView 
android:id="@+id/numberId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/numberId"
android:textSize="22sp"
android:textColor="#fff"
android:textStyle="bold"
android:layout_marginTop="3dp"
android:layout_marginRight="5dp"
android:layout_alignParentRight="true"
android:background="@drawable/text_background"
/>

然后从布局中移除ImageView,因为您不再需要它了。 希望这有帮助

答案 1 :(得分:0)

我想您要做的就是为TextView创建一个9patch。您需要将9patch设置为TextView的背景。这样,它将始终填充您的TextView内容。