2015-10-31 56 views
0

我使用myLinearLayout.setBackgroundResource(R.drawable.my_drawable)设置LinearLayout的背景。有什么方法可以在使用此方法时保持源图像的纵横比(在必要时缩放以适合),而不是让图像伸展以适合LinearLayout使用LinearLayout.setBackgroundResource()保持纵横比()

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); 

回答

2

当我必须设置布局的背景(允许其命名为Layout_A),我使用的RelativeLayout作为家长和里面我把2项:

  • 与scaletype设置的ImageView到centercrop
  • 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); 
+0

我用这个答案,但是对于根元素:http:// stackov用'FrameLayout'而不是'RelativeLayout' erflow.com/q/22875453/1438339。在实践中,可能没有什么区别,或者我应该想象得很好。 –