给你的世界加点颜色
从本章开始改用Markdown编辑器来写博客
目标人群:没有基础的安卓初学者
知识点:layout的简单介绍及TextView的简单介绍
目标:在模拟器上显示出红色颜色的Hello World
简介
本章会简单的介绍关于在布局文件TextView控件的属性设置
正文
1.在Android Studio中打开res/layout/activity_main.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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
每个节点都是由”<”和”/>组成的,遵循标准的xml结构,更多xml请参考XML 教程
作为入门者,需要牢记两种layout:RelativeLayout和LinearLayout,前者是相对布局后者为线性布局,具体细节后面会讲到
- 在此文件的RelativeLayout布局内部显示的是一个TextView控件,即文字显示控件,你可以对其的文字内容和颜色等属性进行设置
2.在res/values/目录下新建文件color,具体方式如下图所示
将该文件命名为color即可,随后打开color.xml,添加红色对应色值
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red">#FF0000</color>
</resources>
3.回到activity_main.xml,在TextView中插入android:textColor=”@color/red”,插入后的代码段应类似于如下所示
<TextView
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:textColor="@color/red"
android:layout_height="wrap_content" />
4.重新Build你的Apk并在模拟器上运行,最后的效果如下图所示