我是Android编程新手。我有一个带有一些 TextView
和 Button
控件的UI。如何在这些组件后面设置一个背景?我们称之为 background.png
。
android:background="@drawable/background"
即可。这将设置您的布局的背景,假设您在/drawable文件夹中拥有该图像。< 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>
首先你需要将 background.png
图片放在 res/drawable/
文件夹中。然后为你的 TextView
和 Button
小部件设置一个父布局。我会给你考虑一个 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>
你可以在XML文件或Java文件中设置背景颜色/可绘制对象。
在XML文件中更改背景
android:background
负责设置视图的背景。因此,如果您想将背景设置为任何View
,请添加此代码。例如,在顶部的LinearLayout
、RelativeLayout
或TextView
或Button
等视图中,具体取决于您的要求。
android:background="@drawable/background"
从Java文件中更改背景
使用setBackgroundResource
将背景设置为任何视图。
或者,如果您想更改视图的颜色,则必须使用setBackgroundColor
。
请看一下: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>
首先,在您的项目选项卡中右键单击“Drawable”文件夹。 选择新建->图像资产,然后选择您的图像。
在xml文件的布局代码中,设置android:background="@Drawable/background.png"
首先复制您想要设置为背景的高分辨率图像,然后将其粘贴(在Drawable文件夹上右键单击)。
然后将布局属性设置如下 android:background="@drawable/Yourimagefilename"
在XML中使用android:background="@drawable/yourBG"。
yourLayout.setBackgroundResource(resid);
或者使用 yourLayout.setBackgroundDrawable(drawble) 方法;
你也可以通过编程方式添加背景图片:
getWindow().setBackgroundDrawableResource(R.drawable.your_image);