android View.setBackground()如何工作?

问题描述:

我正面临一个问题。在一个活动中,我有两个线性布局。第一个人的身高是300dp,第二个人的身高是150dp。我从1024 X 615资源图像创建一个BitmapDrawable。但问题是,当我使用BitmapDrawable作为背景时,通过setBackground()方法,BitmapDrawable在两个布局中显示相同的长度,其中第一个布局背景图像的长度应该从第二个布局延长两倍。布局之间有一些空间,但图像长度相同。android View.setBackground()如何工作?

这里是xml代码。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      xmlns:tools="http://schemas.android.com/tools" 
      android:layout_width="fill_parent" 
      android:layout_height="match_parent" 
      android:paddingLeft="@dimen/activity_horizontal_margin" 
      android:paddingRight="@dimen/activity_horizontal_margin" 
      android:paddingTop="@dimen/activity_vertical_margin" 
      android:paddingBottom="@dimen/activity_vertical_margin" 
      tools:context=".MainActivity" 
      android:orientation="vertical"> 


<LinearLayout 
      android:layout_width="fill_parent" 
      android:layout_height="300dp" 
      android:id="@+id/rel1" 
      android:orientation="vertical" 
    > 

     </LinearLayout> 

<TextView 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:textAppearance="?android:attr/textAppearanceMedium" 
      android:text="Divider" 
      android:id="@+id/textView" 
      android:gravity="center_horizontal"/> 

<LinearLayout 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="150dp" 
    android:id="@+id/ln2" 
    > 

</LinearLayout> 

代码中的onCreate()

Bitmap background = BitmapFactory.decodeResource(getResources(), R.drawable.section_background); 
    BitmapDrawable backGroundBitmap = new BitmapDrawable(getResources(), background); 
    BitmapDrawable backGroundBitmap2 = new BitmapDrawable(getResources(), background); 
    findViewById(R.id.ln2).setBackground(backGroundBitmap); 
    findViewById(R.id.rel1).setBackground(backGroundBitmap); 

这是输出的屏幕截图:output

这是预期的输出:expected

如果我声明的背景xml中的资源输出为ex反恐执行局。如果我在2布局中分别使用“backGroundBitmap”和“backGroundBitmap2”,则输出如预期的那样。

findViewById(R.id.ln2).setBackground(backGroundBitmap); 
    findViewById(R.id.rel1).setBackground(backGroundBitmap2); 

任何人都可以解释为什么会发生这种情况。提前致谢。

为此,您需要使用NinePatchDrawable,以便它将调整其大小以适应视图。引用文档:

NinePatchDrawable 
================= 

A resizeable bitmap, with stretchable areas that you define. 
This type of image is defined in a .png file with a special format. 

有关如何创建图像的更多特定信息,请访问Draw-9 Patch