0

我有一个有两个孩子的 relativeLayout:两个文本视图,一个在另一个之下。有relativeLayout作为wrap_content高度规则。

现在这relative_layout有一个背景,800x500所以它把这个500高度像素作为它的高度。我必须裁剪它,给出150dp一个高度规则来容纳两个文本视图,而不会浪费比需要更多的空间。

我如何使用该背景,但使relativeLayouta 的高度真实wrap_content

 <RelativeLayout
        android:id="@+id/mid"
        android:layout_below="@id/top"
        android:layout_width="wrap_content"
        android:layout_height="130dp" /*if i have wrap_content here it take 500px as height */
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="5dp"
        android:paddingLeft="10dp"
        android:background="@drawable/counter_background2" // 800x500>

            <TextView
                android:id="@+id/CounterMechanicsTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="10dp"
                android:textSize="30dp"
                android:text="@string/mechanics" />

            <TextView
                android:id="@+id/CounterMechanics"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/CounterMechanicsTitle"
                android:layout_marginTop="5dp"
                android:textSize="20dp"
                android:text="@string/mechanics" />

        </RelativeLayout>
4

1 回答 1

1

好的,这是一种方法:

    TextView CounterMechanicsTitle = (TextView) findViewById(R.id.CounterMechanicsTitle);
    TextView CounterMechanics = (TextView) findViewById(R.id.CounterMechanics);
    Drawable dr = getResources().getDrawable(R.drawable.counter_background2);
    RelativeLayout rl = (RelativeLayout) findViewById(R.id.mid);

    int heightOfTextViews = CounterMechanicsTitle.getHeight() + CounterMechanics.getHeight();
    //Now you have the height of the two TextViews

    Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
    // Scale the drawable to heightOfTextViews *1.6 x heightOfTextViews, so to be scaled properly
    Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, heightOfTextViews*1.6, heightOfTextViews, true));

rl.setBackground(d);
    //Optional 
    //rl.getLayoutParams().height = heightOfTextViews;
    //rl.getLayoutParams().width = heightOfTextViews*1.6;

看看这是否解决了它。

于 2013-07-24T14:44:39.437 回答