Android每日范例——背景修改

这篇博客介绍了如何在Android中修改背景,包括使用color.xml文件定义的颜色属性以及引用drawable资源作为背景。通过XML文档设置和AVD运行后的实际显示效果,详细展示了背景修改的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景色修改方式
1、修改xml布局文件中的background属性
2、在java代码中获取控件实例,使用setBackgroundColor方法设置控件颜色
setBackground方法设置图片背景
方式一:修改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"
    <!-- 这是background属性,使用在整个关系布局中 -->
    android:background="@color/red"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textview"
        <!-- 这是background属性,使用在TextView控件中 -->
        android:background="@color/blue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

背景可以引用资源文件color.xml文件定义的属性,也可以引用其他图片drawable资源

方式二:修改java代码
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView)findViewById(R.id.textview);
    textView.setText(R.string.modify);

    textView.setBackgroundColor(R.color.green);
}

xml文档的显示效果
xml文档的显示效果
运行AVD之后的显示效果
运行后

注:
在res/values下新建color.xml资源文件
内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="red">#FF0000</color>
    <color name="green">#00FF00</color>
    <color name="blue">#0000FF</color>
</resources>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值