Android UI 开发
Android的常见控件的核心是两个类:
android.view.Viewandroid.view.ViewGroup
View 类表示通用的 View 对象。Android中的常用控件最终会扩展View 类。
ViewGroup 是一个视图,它包含其他视图。 ViewGroup 是布局类列表的基类。
布局
Android使用布局的概念来管理如何在容器视图内布置控件。
你可以从多种方法中选择一种在Android中构建UI。
- 你可以在代码中完全构建UI。
- 你也可以使用XML定义UI。
- 你甚至可以在XML中的合并双定义UI,然后在代码中进行引用、修改。
通用布局属性
每个 View 和 ViewGroup 都有一组通用属性。
- layout_width指定View或ViewGroup的宽度
- layout_height指定View或ViewGroup的高度
- layout_marginTop指定View或ViewGroup顶部的额外空间
- layout_marginBottom指定View或ViewGroup底部的额外空间
- layout_marginLeft指定View或ViewGroup左侧的额外空间
- layout_marginRight指定View或ViewGroup右侧的额外空间
- layout_gravity指定子视图的位置
- layout_weight指定布局中应分配给View的额外空间量
- layout_x指定View或ViewGroup的x坐标
- layout_y指定View或ViewGroup的y坐标
注意
layout_weight 和 layout_gravity 属性仅在View位于LinearLayout 或 TableLayout中时才适用。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
例如,<TextView> 元素的宽度使用fill_parent常量填充其父对象的整个宽度。
其高度由 wrap_content常量指示,这意味着它的高度是其内容的高度(在这种情况下,其中包含的文本)。
如果你不想让<TextView> 视图占据整行,你可以将其layout_width 属性设置为 wrap_content ,如下所示:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello" />
上述代码将设置视图的宽度等于其中包含的文本的宽度。
将布局xml连接到Java代码
将activity连接到UI(main_layout_xml_file.xml)的代码是 setContentView()方法:
package cn.w3cschool.app;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
将以下代码以粗体添加到 res/layout/,在你的主xml文件中进行布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is my first Android Application!" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="And this is a clickable button!" />
</LinearLayout>

R.layout.main是指位于res/layout文件夹中的main.xml文件。
当你向 res/layout 文件夹中添加其他XML文件时,文件名将自动在 R.java 文件中生成。
onCreate()方法是在加载activity时触发的许多方法之一。