【问题标题】:How android View.setBackground() works?android View.setBackground() 如何工作?
【发布时间】:2015-09-06 23:20:45
【问题描述】:

我遇到了一个问题。在一个活动中,我有两个线性布局。第一个的高度是 300dp,第二个的高度是 150dp。我从 1024 X 615 资源图像创建了一个 BitmapDrawable。但问题是当我通过 setBackground() 方法使用 BitmapDrawable 作为背景时,BitmapDrawable 在两种布局中显示相同的长度,其中第一个布局背景图像的长度应该是第二个的两倍。布局之间有一些空间,但图像长度相同。

这里是 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);

这是输出截图:

这是预期的输出:

如果我在 xml 中声明背景资源,则输出符合预期。如果我在 2 布局中分别使用“backGroundBitmap”和“backGroundBitmap2”,则输出符合预期。

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

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

【问题讨论】:

    标签: android setbackground


    【解决方案1】:

    为此,您需要使用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,了解有关如何创建图像的更多具体信息。

    【讨论】:

      猜你喜欢
      • 2013-12-30
      • 2014-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-23
      • 2012-10-11
      • 2012-12-07
      • 2012-11-23
      相关资源
      最近更新 更多