-
背景色修改方式
-
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文档的显示效果
运行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>