15 用户界面(User Interface)
线性布局(LinearLayout)
示例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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/name_text"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancle_button"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ok_button"/>
</LinearLayout>
其对应strings.xml内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, UIActivity!</string>
<string name="app_name">用户界面</string>
<string name="name_text">请输入用户名</string>
<string name="ok_button">确定</string>
<string name="cancle_button">取消</string>
</resources>
示例main.xml布局文件如下,其对应的strings.xml内容不变。
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="@string/name_text"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancle_button"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ok_button"/>
</LinearLayout>
15.2.2 RelativeLayout(相对布局)
相对布局中的视图组件是按相互之间的相对位置来确定的,并不是线性布局中的必须按行或按列单个显示。示例布局文件如下:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/name_text"
android:id="@+id/text"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/text"
android:id="@+id/edit"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancle_button"
android:layout_alignParentRight="true"
android:layout_below="@id/edit"
android:id="@+id/cancle"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/cancle"
android:layout_alignTop="@id/cancle"
android:text="@string/ok_button"/>
</RelativeLayout>
15.2.3 线性布局与相对布局嵌套使用
布局之间可以相互嵌套使用,以完成更为复杂的布局效果。举例来说,下面是一个线性布局,当中包含了相对布局的界面。
<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/name_text"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<Button
android:layout_width=" wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancle_button"
android:layout_alignParentRight="true"
android:id="@+id/cancle"/>
<Button
android:layout_width=" wrap_content "
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/cancle"
android:layout_alignTop="@id/cancle"
android:text="@string/ok_button"/>
</RelativeLayout>
</LinearLayout>
15.2.4 表格布局(TableLayout)
示例布局文件内容如下:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="0,1,2,3"
>
<TableRow>
<TextView
android:text="@string/name"
android:gravity="center"
android:padding="3dip" />
<TextView
android:text="@string/gender"
android:gravity="center"
android:padding="3dip" />
<TextView
android:text="@string/age"
android:gravity="center"
android:padding="3dip" />
<TextView
android:text="@string/phonenum"
android:gravity="center"
android:padding="3dip" />
</TableRow>
<TableRow>
<TextView
android:text="@string/name1"
android:gravity="center"
android:padding="3dip" />
<TextView
android:text="@string/gender1"
android:gravity="center"
android:padding="3dip" />
<TextView
android:text="@string/age1"
android:gravity="center"
android:padding="3dip" />
<TextView
android:text="@string/phonenum1"
android:gravity="center"
android:padding="3dip" />
</TableRow>
<TableRow>
<TextView
android:text="@string/name2"
android:gravity="center"
android:padding="3dip" />
<TextView
android:text="@string/gender1"
android:gravity="center"
android:padding="3dip" />
<TextView
android:text="@string/age2"
android:gravity="center"
android:padding="3dip" />
<TextView
android:text="@string/phonenum2"
android:gravity="center"
android:padding="3dip" />
</TableRow>
</TableLayout>
对应的strings.xml文件内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="name">姓名</string>
<string name="gender">性别</string>
<string name="age">年龄</string>
<string name="phonenum">电话</string>
<string name="gender1">男</string>
<string name="gender2">女</string>
<string name="name1">张三</string>
<string name="age1">25</string>
<string name="phonenum1">1234567</string>
<string name="name2">李四</string>
<string name="age2">24</string>
<string name="phonenum2">7654321</string>
</resources>
15.2.5 帧布局(FrameLayout)
1.main.xml文件其内容如下:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/frame">
</FrameLayout>
2.编写BirdActivity.java类
代码如下:
public class BirdActivity extends Activity {
FrameLayout frame = null;
private boolean flag = true;
//由该类两个方法间的循环调用,实现界面不断更新
class MyHandler extends Handler{
int i = 0;
public void handleMessage(Message msg) {
i++;
//总共三幅图,依次显示
show(i % 3);
//再次调用sleep方法
sleep(10);
}
public void sleep(long delayMillis) {
//判断是否继续飞翔
if(flag) {
//实质上是调用了一次handleMessage
sendMessageDelayed(obtainMessage(0), delayMillis);
}
}
}
//该方法是被调用以更新帧布局的前景图片
void show(int j) {
//获取三张图片
Drawable a = getResources().getDrawable(R.drawable.a);
Drawable b = getResources().getDrawable(R.drawable.b);
Drawable c = getResources().getDrawable(R.drawable.c);
//不同的情况,设置不同的前景
switch (j) {
case 0:
frame.setForeground(a);
break;
case 1:
frame.setForeground(b);
break;
case 2:
frame.setForeground(c);
break;
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
frame = (FrameLayout) findViewById(R.id.frame);
//创建一个Handler子类对象,要调用其方法
final MyHandler myHandler = new MyHandler();
myHandler.sleep(10);
//为fram设置单击事件,当其被单击时,在飞翔与暂停飞翔间切换
frame.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
flag = !flag;
myHandler.sleep(10);
}
});
}
}
15.3 菜单(Menu)
编写MenuActivity.java:
package com.sharpandroid.menu;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MenuActivity extends Activity {
private static final int OK = 1;
private static final int CANCLE = 2;
private static final int ABOUT = 3;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
//当单击Menu键时会打开菜单,当菜单第一次被打开始,框架回调该方法
public boolean onCreateOptionsMenu(Menu menu) {
//为菜单添加一个id为1,标题为“开始”的元素
menu.add(0, OK, 0, "开始");
menu.add(0, CANCLE, 0, "取消");
//为菜单添加一个子菜单,id为3,标题为“关于”,并返回该子菜单对象为file
Menu file = menu.addSubMenu(0, ABOUT, 0, " 关于");
//得到一个MenuInflater对象
MenuInflater inflater = getMenuInflater();
//调用inflater的inflate方法,获取资源文件中定义的元素
//并将这些元素添加进指定的Menu——file
inflater.inflate(R.menu.submenubyxml, file);
return true;
}
@Override
//当一个菜单项被选中时,框架回调该方法,并将被单击的Item传入
public boolean onOptionsItemSelected(MenuItem item) {
//根据被选中的Item进行不同的处理
switch (item.getItemId()) {
case OK:
this.setTitle("开始");
return true;
case CANCLE:
this.setTitle("取消");
return true;
case ABOUT:
this.setTitle("关于");
return true;
case R.id.help:
this.setTitle("帮助信息");
return true;
case R.id.our:
this.setTitle("联系我们");
return true;
}
return false;
}
}
15.4 常用UI控件(Widgets)
15.4.1 单选框(RadioButton)
在布局文件中的应用示例如下:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:checkedButton="@+id/woman"
android:id="@+id/sex">
<RadioButton
android:text="@string/man"
android:id="@+id/man"
/>
<RadioButton
android:text="@string/woman"
android:id="@id/woman" />
</RadioGroup>
</LinearLayout>
15.4.2 多选框(CheckBox)
编写main.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="@dimen/TextViewWidth"
android:layout_height="wrap_content"
android:text="@string/favoriteString"
android:textSize="@dimen/fontSize"
android:id="@+id/favorite"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/favorite"
android:text="@string/pingpang"
android:id="@+id/checkboxpingpang"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/checkboxpingpang"
android:text="@string/football"
android:id="@+id/checkboxfootball"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/favorite"
android:layout_below="@id/checkboxfootball"
android:text="@string/basketball"
android:id="@+id/checkboxbasketball"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/checkboxbasketball"
android:layout_alignTop="@id/checkboxbasketball"
android:text="@string/tennis"
android:id="@+id/checkboxtennis"/>
</RelativeLayout>
15.4.3 列表显示(ListView)
编写string.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, ListViewActivity!</string>
<string name="app_name">ListView示例</string>
<string name="name">姓名</string>
</resources>
编写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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/name"
/>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/listview"
></ListView>
</LinearLayout>
编写ListViewActivity.java:
package com.sharpandroid.listview;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class ListViewActivity extends Activity {
private ListView listView;
private String[] name = {"张三","李四","王五","刘六"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.listview);
//创建一个ArrayAdapter
ArrayAdapter adapter =
new ArrayAdapter(this, android.R.layout.simple_list_item_1,name);
listView.setAdapter(adapter);
//listView注册一个元素单击事件监听器
listView.setOnItemClickListener(new AdapterView.
OnItemClickListener() {
@Override
//当某个元素被单击时调用该方法
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2,long arg3) {
Toast.makeText(ListViewActivity.this,name[arg2] ,
Toast.LENGTH_LONG).show();
}
});
}
}
编写ListViewActivity.java,内容如下:
package com.sharpandroid.listview;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class ListViewActivity extends ListActivity {
private String[] name = { "张三", "李四", "王五", "刘六" };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 创建一个ArrayAdapter
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, name);
setListAdapter(adapter);
}
protected void onListItemClick(ListView l, View v, int position,
long id) {
Toast.makeText(ListViewActivity.this, name[position],Toast.
LENGTH_LONG).show();
}
}
15.4.4 下拉列表框(Spinner)
编写arrays.xml,定义Spinner中需要显示的数据:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="colors">
<item>red</item>
<item>orange</item>
<item>yellow</item>
<item>green</item>
<item>blue</item>
<item>violet</item>
</string-array>
</resources>
编写main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/color"
/>
<Spinner android:id="@+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="@string/color_prompt"
android:entries="@array/colors"
/>
</LinearLayout>
15.4.5 进度条(ProgressBar)
编写strings.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, ProgressBarActivity!</string>
<string name="app_name">进度条示例</string>
<string name="progressbar1">环形进度条</string>
<string name="progressbar">水平进度条</string>
</resources>
编写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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/progressbar1"
/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progress_bar1"
></ProgressBar>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/progressbar"
/>
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/progress_bar"
></ProgressBar>
</LinearLayout>
编写ProgressBarActivity.java文件:
package com.sharpandroid.progress;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
public class ProgressBarActivity extends Activity {
private ProgressBar mProgress;
private int mProgressStatus = 0;
//创建一个Handler对象
private Handler mHandler = new Handler();
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mProgress = (ProgressBar) findViewById(R.id.progress_bar);
//设定进度条的最大值,其将为该进度条显示的基数
mProgress.setMax(10000);
//新开启一个线程
new Thread(new Runnable() {
public void run() {
//循环10000次,不停地更新mProgressStatus的值
while (mProgressStatus ++< 10000) {
//将一个Runnable对象添加到消息队列当中,
//并且当执行到该对象时执行run()方法
mHandler.post(new Runnable() {
public void run() {
//重新设置进度条当前的值
mProgress.setProgress(mProgressStatus);
}
});
}
}
}).start();
}
}
15.4.6 拖动条(SeekBar)
编写strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, SeekBarActivity!</string>
<string name="app_name">拖动条示例</string>
<string name="speed">播放进度:</string>
</resources>
编写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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/speed"
android:id="@+id/speed"
/>
<SeekBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/seek_bar"
/>
</LinearLayout>
编写SeekBarActivity.java类:
package com.sharpandroid.seekbar;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.SeekBar;
import android.widget.TextView;
public class SeekBarActivity extends Activity {
private SeekBar seekBar ;
private TextView textView;
//标记是否需要刷新
private boolean flag=true;
private Handler mHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
seekBar = (SeekBar) findViewById(R.id.seek_bar);
textView = (TextView) findViewById(R.id.speed);
//设定拖动条的最大值,其为该拖动条显示的基数
seekBar.setMax(100);
//该方法为seekBar注册一个监听,当SeekBar发生改变时调用参数l中的对应方法
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChange
Listener() {
@Override
//当游标移动停止时调用该方法
public void onStopTrackingTouch(SeekBar seekBar) {
//设置标记为需要刷新
flag = true;
//刷新
refresh();
}
@Override
//当游标开始移动时调用该方法
public void onStartTrackingTouch(SeekBar seekBar) {
//停止刷新
flag = false;
}
@Override
//当进度条游标被改变或者进度更改时调用该方法
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
//更改textView的内容
textView.setText("进度为:" + progress + " %");
}
});
//创建时就开始自动更新该拖动条
refresh();
}
//该方法自动刷新拖动条的进度值
private void refresh(){
new Thread(new Runnable() {
public void run() {
//当进度不到100,就更新mProgressStatus的值
while (flag && seekBar.getProgress()< 100) {
try {
//暂停1秒
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//将一个Runnable对象添加到消息队列当中
//并且当执行到该对象时执行run()方法
mHandler.post(new Runnable() {
public void run() {
//重新设置进度条当前的值,加1
seekBar.setProgress(seekBar.getProgress() + 1);
}
});
}
}
}).start();
}
}
15.5 常用的几种通知
15.5.1 状态栏通知
2.编写strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, NotificationActivity!</string>
<string name="app_name">状态栏通知</string>
<string name="send">发送通知</string>
</resources>
3.编写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"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/send"
android:id="@+id/button"
/>
</LinearLayout>
4.编写NotificationActivity.java
package com.sharpandroid.notification;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class NotificationActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//获取通知管理器
NotificationManager mNotificationManager = (Notification
Manager) getSystemService(Context.NOTIFICATION_SERVICE);
int icon = android.R.drawable.sym_action_email;
long when = System.currentTimeMillis();
//新建一个通知,指定其图标和标题
//第一个参数为图标,第二个参数为标题,第三个为通知时间
Notification notification = new Notification(icon, null,
when);
notification.defaults = Notification.DEFAULT_SOUND;
//发出默认声音
//当单击消息时就会向系统发送openintent意图
PendingIntent contentIntent = PendingIntent.getActivity
(NotificationActivity.this, 0, null, 0);
notification.setLatestEventInfo(NotificationActivity.
this, "开会通知","今天下午4点到会议室开会!", contentIntent);
mNotificationManager.notify(0, notification);//发送通知
}
});
}
}
15.5.2 警告对话框
编写strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, AlertDialogActivity!</string>
<string name="app_name">警告对话框</string>
<string name="button">弹出对话框</string>
</resources>
编写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"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button"
android:id="@+id/button"
/>
</LinearLayout>
编写AlertDialogActivity.java:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
复制完成之后,根据我们的需要修改一部分内容之后的AlertDialogActivity.java类的代码如下。
package com.sharpandroid.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class AlertDialogActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder =
new AlertDialog.Builder(AlertDialogActivity.this);
builder.setTitle("sharpandroid")
.setMessage("你确定要访问Android网站吗?")
.setCancelable(false)
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
//创建一个访问“http://www.android.com”网站的意图
//该意图会告知系统打开浏览器,并访问该网址
Intent intent =
new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.android.com"));
startActivity(intent);
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel(); //删除对话框
}
});
AlertDialog alert = builder.create();//创建对话框
alert.show();//显示对话框
}
});
}
}
将创建AlertDialog的代码优化为如下所示。
new AlertDialog.Builder(AlertDialogActivity.this)
.setTitle("sharpandroid")
.setMessage("你确定要访问Android网站吗?")
.setCancelable(false)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//创建一个访问“http://www.android.com”网站的意图
//该意图会告知系统打开浏览器,并访问该网址
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.android.com"));
startActivity(intent);
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel(); //删除对话框
}
}).show();//显示对话框
15.6 UI综合应用——用户注册
编写strings.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<resources>
<string name="hello">Hello World, LoginActivity!</string>
<string name="app_name">用户注册界面</string>
<string name="nameString">用户名:</string>
<string name="ageString">年龄:</string>
<string name="registerButtonText">注册</string>
<string name="sexString">性别:</string>
<string name="favoriteString">喜好:</string>
<string name="cityString">城市:</string>
<string name="passString">密码:</string>
<string name="pingpang">乒乓球</string>
<string name="basketball">篮球</string>
<string name="football">足球</string>
<string name="tennis">网球</string>
</resources>
新建了一个资源文件parameters.xml,存放一些属性信息,如字体大小、TextView以及EditText的宽度。代码内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="fontSize">22px</dimen>
<dimen name="TextViewWidth">90px</dimen>
<dimen name="EditTextWidth">160px</dimen>
</resources>
编写main.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">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="@dimen/TextViewWidth"
android:layout_height="wrap_content"
android:text="@string/nameString"
android:textSize="@dimen/fontSize"
android:id="@+id/name"/>
<EditText
android:layout_width="@dimen/EditTextWidth"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/name"
android:layout_alignTop="@id/name"
android:id="@+id/nameValue"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="@dimen/TextViewWidth"
android:layout_height="wrap_content"
android:text="@string/passString"
android:textSize="@dimen/fontSize"
android:id="@+id/pass"/>
<EditText
android:password="true"
android:layout_width="@dimen/EditTextWidth"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/pass"
android:layout_alignTop="@id/pass"
android:id="@+id/passValue"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="@dimen/TextViewWidth"
android:layout_height="wrap_content"
android:text="@string/ageString"
android:textSize="@dimen/fontSize"
android:id="@+id/age"/>
<EditText
android:numeric="integer"
android:layout_width="@dimen/EditTextWidth"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/age"
android:layout_alignTop="@id/age"
android:id="@+id/ageValue"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="@dimen/TextViewWidth"
android:layout_height="wrap_content"
android:text="@string/sexString"
android:textSize="@dimen/fontSize"
android:id="@+id/sex"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/sex"
android:checkedButton="@+id/radioMan"
android:orientation="horizontal"
android:id="@+id/sexMenu">
<RadioButton android:text="男" android:id="@id/radioMan"/>
<RadioButton android:text="女" android:id="@+id/radioWoman"/>
</RadioGroup>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="@dimen/TextViewWidth"
android:layout_height="wrap_content"
android:text="@string/favoriteString"
android:textSize="@dimen/fontSize"
android:id="@+id/favorite"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/favorite"
android:text="@string/pingpang"
android:id="@+id/checkboxpingpang"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/checkboxpingpang"
android:text="@string/football"
android:id="@+id/checkboxfootball"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/favorite"
android:layout_below="@id/checkboxfootball"
android:text="@string/basketball"
android:id="@+id/checkboxbasketball"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/checkboxbasketball"
android:layout_alignTop="@id/checkboxbasketball"
android:text="@string/tennis"
android:id="@+id/checkboxtennis"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="@dimen/TextViewWidth"
android:layout_height="wrap_content"
android:text="@string/cityString"
android:textSize="@dimen/fontSize"
android:id="@+id/city"/>
<Spinner
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/city"
android:id="@+id/cityItems">
</Spinner>
</RelativeLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/registerButtonText"
android:id="@+id/registerButton"/>
</LinearLayout>
编写LoginActivity.java:
package com.sharpandroid.UserLogin;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
public class LoginActivity extends Activity {
private static final String[] cities = { "北京", "上海", "广州", "郑州"};
private EditText name, age, pass;
private Button regButton;
private RadioGroup sexRadioGroup;
private CheckBox basketball, football, pingpang, tennis;
private Spinner cityItems;
private boolean flag = true;
private List<CheckBox> favorities;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//定义一个ArrayList,用来存放所有的CheckBox
favorities = new ArrayList<CheckBox>();
//得到相应的显示控件的对象
name = (EditText) findViewById(R.id.nameValue);
age = (EditText) findViewById(R.id.ageValue);
pass = (EditText) findViewById(R.id.passValue);
regButton = (Button) findViewById(R.id.registerButton);
cityItems = (Spinner) findViewById(R.id.cityItems);
sexRadioGroup = (RadioGroup) findViewById(R.id.sexMenu);
basketball = (CheckBox) findViewById(R.id.checkboxbasketball);
//将basketball对象添加到favorities中
favorities.add(basketball);
football = (CheckBox) findViewById(R.id.checkboxfootball);
favorities.add(football);
pingpang = (CheckBox) findViewById(R.id.checkboxpingpang);
favorities.add(pingpang);
tennis = (CheckBox) findViewById(R.id.checkboxtennis);
favorities.add(tennis);
//创建一个数组型适配器
ArrayAdapter<String> adpter = new ArrayAdapter<String>(
LoginActivity.this, android.R.layout.simple_spinner_item,
cities);
adpter.setDropDownViewResource(android.R.layout.simple_spinner_
dropdown_item);
cityItems.setAdapter(adpter);
//为regButton注册一个单击事件监听器
regButton.setOnClickListener(new View.OnClickListener() {
//当按钮被单击时调用该方法
@Override
public void onClick(View v) {
flag = addUser();
if (flag)
//创建一个AlertDialog对话框显示登录的信息。
new AlertDialog.Builder(LoginActivity.this).setTitle(
"请确认信息").setMessage(
"你的信息如下:" + "\n" + "姓名:"
+ name.getText().toString() + "\n" + "年龄:"
+ age.getText().toString() + "\n" + "性别:"
+ getSex() + "\n" + "爱好:" + getFavorite()
+ "\n" + "城市:" + getCity() + "\n")
.setCancelable(false).setPositiveButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int id) {
ProgressDialog.show(
LoginActivity.this,
"用户信息注册中", "请等待……")
.setCancelable(true);
}
}).setNegativeButton("修改",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int id) {
dialog.cancel(); // 删除对话框
}
}).show();// 显示对话框
}
});
}
//获取Spinner中的值
private String getCity() {
return cities[cityItems.getSelectedItemPosition()];
}
//获取CheckBox的值
private String getFavorite() {
String favString = "";
for (CheckBox cb : favorities) {
if (cb.isChecked()) {
favString += cb.getText().toString();
favString += ",";
}
}
if (favString != "") {
favString = favString.substring(0, favString.length() - 1);
} else {
favString = "你没有选择爱好!";
}
return favString;
}
//获取一组RadioGroup中被选中的RadioButton的值
private String getSex() {
RadioButton mRadio = (RadioButton) findViewById(sexRadioGroup
.getCheckedRadioButtonId());
return mRadio.getText().toString();
}
/**
* 拼写检测,检测输入内容是否合乎要求
*/
public boolean addUser() {
if (name.getText().toString().length() == 0) {
name.setError("用户名不能为空");
return false;
}
if (age.getText().toString().length() == 0) {
age.setError("年龄不能为空");
return false;
}
if (pass.getText().toString().length() == 0) {
pass.setError("密码不能为空 ");
return false;
}
return true;
}
}
15.7 硬编码生成界面
编写DynamicLayoutActivity.java:
package com.sharpandroid.dlayout;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
public class DynamicLayoutActivityDynamic extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
LinearLayout.LayoutParams layoutparams =
new LinearLayout.LayoutParams
(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
setContentView(layout, layoutparams);
TextView textView = new TextView(this);
textView.setText("我从java代码中来,而不是XML布局文件!");
LinearLayout.LayoutParams textViewparams =
new LinearLayout.LayoutParams
(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
layout.addView(textView, textViewparams);
}
}
15.9 程序界面自动适应屏幕分辨率
3.编写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"
>
<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="320x240"
/>
</LinearLayout>
5.编写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"
>
<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="480x320"
/>
</LinearLayout>