大致可以认为,Android APP由两部分组成,布局、属性部分和逻辑代码部分。属性和布局负责Android APP的UI,即用户看到的部分,由XML语言编写,逻辑代码部分则由Java语言编写,负责APP的逻辑控制工作。
新建一个Android项目,查看左侧的Android项目文件结构如图3.1所示。
图3.1 Android项目文件结构
最外层的根目录为app,app目录中有三个子文件夹:
manifests文件夹:Android系统配置文件夹,包含一个AndroidManifest.xml文件;
java文件夹:存放Java代码的文件夹,新建项目时默认生成了三个文件夹,com.first.project文件夹用来存放Java文件,这里包含一个名为MainActivity的Java文件,是新建项目时默认生成的。第二个和第三个文件为测试代码文件夹,不是十分常用。
res文件夹:存放Android项目的资源文件,包含四个文件夹:drawable(图片资源文件夹)、layout(布局资源文件夹)、mipmap(图片资源文件夹,存放项目图标)、values(存放数值资源文件)。
3.1.1 布局属性
本章主要讲Android的属性和布局知识,下面我们着重看一下这个默认的activity_ma-in.xml布局文件:
<?xml version="1.0" encoding="utf-8"?>
<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: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="com.first.project.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
默认的布局文件采用RelativeLayout相对布局,在相对布局中仅添加了一个TextView文本控件,布局文件中默认生成的一些属性不太常用,可以手动去除,去除后代码如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
最上方的<?xml version="1.0" encoding="utf-8"?>是xml文件的title,里面的version表示xml版本号;encoding表示文本编码类型,这里默认设置为utf-8。
RelativeLayout是父布局的标签,表示相对布局,对于相对布局后面的章节还会详细介绍;对于xmlns属性的全称应该是xmlnamespace,添加了这个属性才可以使用android的属性(即android:开头的属性);layout_width表示父布局的宽属性,属性值为match_parent表示占据整个界面的宽;layout_height表示父布局的高属性,属性值为match_parent表示占据整个界面的高。