2010-04-26 57 views
26

我有一个LinearLayout它有一个背景图像(9修补png文件)。 如何将填充添加到左侧和右侧,以便背景图像不占据整个宽度?我试过android:paddingLeftandroid:paddingRight,但这并没有改变任何东西。如何为背景图像添加填充

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:paddingLeft="25dip" 
    android:paddingRight="25dip" 
    android:background="@drawable/background"> 

整个背景仍然延伸整个屏幕宽度。

回答

3

这不起作用,因为填充仅对LinearLayout的内容起作用。通过在这个内部使用第二个LinearLayout,填充将生效。您必须定义将在填充区域中可见的第一个LinearLayout的背景颜色。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:paddingLeft="25dip" 
    android:paddingRight="25dip" 
    android:background="#FF000000"> 

    <LinearLayout 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="@drawable/background"> 

    </LinearLayout> 

</LinearLayout> 

注意:这也可能是通过使用XML文件作为背景。

+0

这不是那么好,因为它增加了层次深度。你能否详细说明如何用XML实现这个答案? – 2013-04-25 17:36:53

+0

我已经发布了另一个使用插入drawable的解决方案,所以不需要扩展。谢谢。 – 2013-04-26 09:30:52

+1

您可以通过使用FrameLayout更改外部LinearLayout来改善此布局 – vovahost 2014-11-10 16:50:03

83

你应该使用XML绘制,专为这个目的而设计的 - 插图绘制对象http://developer.android.com/guide/topics/resources/drawable-resource.html#Inset

例如:

RES /绘制/ inset_background.xml:

<?xml version="1.0" encoding="utf-8"?> 
<inset xmlns:android="http://schemas.android.com/apk/res/android" 
    android:drawable="@drawable/your_background_image" 
    android:insetRight="25dip" 
    android:insetLeft="25dip" /> 

和然后在你的xml布局中:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="@drawable/inset_background"> 
+0

这对我没有预期的结果,我有同样的确切问题http://stackoverflow.com/questions/26850400/inset-drawable-not-在文档中描述的工作 – 2015-04-29 15:07:28

2

你可以使用

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="horizontal" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:layout_marginLeft="25dip" 
android:layout_marginRight="25dip" 
android:background="@drawable/background"> 
5

乌尔背景绘制应该是这样的,采用了android:底部

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:bottom="48dp" android:drawable="@drawable/bg"> 
    </item> 

</layer-list> 
+0

该解决方案实际上可行! – 2016-09-01 09:56:36

+0

你救了我的人生兄弟。 – viper 2018-02-08 04:58:34