使用LinearLayout.setBackgroundResource()

时间:2015-10-31 18:05:33

标签: android android-layout

我使用myLinearLayout.setBackgroundResource(R.drawable.my_drawable)来设置LinearLayout的背景。有没有办法在使用此方法时保持源图像的宽高比(在必要时缩放以适应),而不是使图像拉伸以适合LinearLayout

xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/background_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    ...

</LinearLayout>

java文件:

backgroundLayout.setBackgroundResource(R.drawable.my_drawable);

1 个答案:

答案 0 :(得分:2)

当我必须设置布局的背景(让我们将其命名为Layout_A)时,我使用RelativeLayout作为父级,并在其中放入2个项目:

  • 将scaletype设置为centercrop的ImageView
  • Layout_A

xml将是:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/background"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@drawable/background"/>

    <Layout_A>

        ...

    </Layout_A>

</RelativeLayout>

您需要更改背景的代码是:

ImageView ivBackground = (ImageView) rootView.findViewById(R.id.background);
ivBackground.setImageDrawable(getResources().getDrawable(R.drawable.my_drawable));

或:

ImageView ivBackground = (ImageView) rootView.findViewById(R.id.background);
ivBackground.setImageResource(R.drawable.my_drawable);
相关问题