如何在Android UI中设置布局背景

8

我是Android编程新手。我有一个带有一些 TextViewButton 控件的UI。如何在这些组件后面设置一个背景?我们称之为 background.png

9个回答

26
在您的父布局元素中,例如LinearLayout或其他元素,只需添加android:background="@drawable/background"即可。这将设置您的布局的背景,假设您在/drawable文件夹中拥有该图像。

3
谢谢。我也找到了这种方法: linearlyaout.setBackgroundResource(R.drawable.FILENAME); 注:FILENAME是指图片的文件名,linearlyaout是指线性布局的名称。 - farissyariati
如果图像不是svg或psd格式,则结果背景可能会降低质量。如何设置背景,使所有设备都不会失去质量? - Samudra Ganguly
@SamudraGanguly 请查看此处的文档 https://developer.android.com/training/multiscreen/screendensities#TaskProvideAltBmp,以提供适用于每个屏幕密度的资源。 - LuxuryMode

2
非常简单。将要显示的图像粘贴到res/drawable-ldpi/文件夹中,然后在您的xml中编写以下内容:
< LinearLayout 

    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myview"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="top"
    android:background="@drawable/icon">
< Button/>

< TextView   />

 
< / LinearLayout>

2

首先你需要将 background.png 图片放在 res/drawable/ 文件夹中。然后为你的 TextViewButton 小部件设置一个父布局。我会给你考虑一个 LinearLayout 作为父布局,代码如下:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:background="@drawable/background.png" 
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
 <TextView    android:layout_width="fill_parent"
              android:layout_height="wrap_content" 
              android:text="@string/hello" />
 <Button      android:text="Button" 
              android:id="@+id/button1"
              android:layout_width="wrap_content" 
              android:layout_height="wrap_content"></Button>
</LinearLayout>

1

你可以在XML文件或Java文件中设置背景颜色/可绘制对象。

  1. 在XML文件中更改背景

    android:background负责设置视图的背景。因此,如果您想将背景设置为任何View,请添加此代码。例如,在顶部的LinearLayoutRelativeLayoutTextViewButton等视图中,具体取决于您的要求。

    android:background="@drawable/background"

  2. 从Java文件中更改背景

    使用setBackgroundResource将背景设置为任何视图。

    或者,如果您想更改视图的颜色,则必须使用setBackgroundColor


1

请看一下:android:background

这是一个示例 XML,您可能需要在此基础上构建。

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:id="@+id/my_view"
    xmlns:android="http://schemas.android.com/apk/res/android"    
    android:layout_width="fill_parent"    
    android:layout_height="fill_parent"    
    android:background="@drawable/background">        
</FrameLayout> 

0

首先,在您的项目选项卡中右键单击“Drawable”文件夹。 选择新建->图像资产,然后选择您的图像。

在xml文件的布局代码中,设置android:background="@Drawable/background.png"


0

首先复制您想要设置为背景的高分辨率图像,然后将其粘贴(在Drawable文件夹上右键单击)。

然后将布局属性设置如下 android:background="@drawable/Yourimagefilename"


0

在XML中使用android:background="@drawable/yourBG"。

yourLayout.setBackgroundResource(resid);

或者使用 yourLayout.setBackgroundDrawable(drawble) 方法;


0

你也可以通过编程方式添加背景图片:

getWindow().setBackgroundDrawableResource(R.drawable.your_image);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接