最近学习android,对于ui设计有个基础的了解。Android的界面设计可以在java代码中实现 也可以在xml文件中实现,xml文件的解析有两种Dom和Sax,设计方面一般用Sax解析xml文件。对于xml的解析,这里不做解释。现在让我们来初步认识认识Android开发的基础UI设计。
假设读者安装好了ADT和Eclipse。首先打开Eclipse,新建一个Android工程,建自己的包名,文件名,和工程名。打开工程目录,打开res/layout目录下的main.xml文件,设计如下
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <EditText android:text="EditText01" android:layout_height="wrap_content"
- android:layout_width="fill_parent" android:id="@+id/edtInput"></EditText>
- <LinearLayout android:id="@+id/LinearLayout01" android:layout_height="wrap_content"
- android:layout_width="fill_parent" android:gravity="center">
- <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
- android:text="Show" android:id="@+id/btnShow"></Button>
- <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
- android:text="Clear" android:id="@+id/btnClear"></Button>
- </LinearLayout>
- </LinearLayout>
上面xml文件LinearLayout 线性布局 ,android的布局还有帧布局,相对布局,表格布局,绝对布局分别是FrameLayout、RelativeLayout 、TableLayout 、AbsoluteLayout。LinearLayout有个orientation属性,是水平布局(vertical)还是垂直布局(Hrizontal )
接下来些java代码,在src\com\example\activitys目录下打开MainActivity.java,添加如下代码:
- package com.studio.android;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- public class HelloAndroid extends Activity {
- /** Called when the activity is first created. */
- Button btnShow;
- Button btnClear;
- EditText edtInput;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- btnShow=(Button)findViewById(R.id.btnShow);//控件的id获得控件
- btnClear=(Button)findViewById(R.id.btnClear);//同上
- edtInput=(EditText)findViewById(R.id.edtInput);// 同上
- btnShow.setOnClickListener(new ClickListener());//注册点击事件
- btnClear.setOnClickListener(new ClickListener());//同上
- }
- class ClickListener implements OnClickListener
- {
- public void onClick(View v)
- {
- if(v==btnShow) //对按钮show的点击事件的响应
- {
- new AlertDialog.Builder(HelloAndroid.this)
- .setIcon(android.R.drawable.ic_dialog_alert)
- .setTitle("Information")
- .setMessage(edtInput.getText())
- .show();
- }
- else if(v==btnClear) //对按钮clear的点击事件的响应
- {
- edtInput.setText("HelloAndroid");
- }
- }
- }
- }