本文实例讲述了android单选按钮对话框用法。分享给大家供大家参考。具体如下:
main.xml布局文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?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= ""
android:id= "@+id/edittext"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
android:editable= "false"
android:cursorvisible= "false" />
<button android:text= "显示单选对话框"
android:id= "@+id/button"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content" />
</linearlayout>
|
array.xml数组
1
2
3
4
5
6
7
8
|
<?xml version= "1.0" encoding= "utf-8" ?>
<resources>
<string-array name= "hobby" >
<item>游泳</item>
<item>打篮球</item>
<item>登山</item>
</string-array>
</resources>
|
alertdialog类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
package com.ljq.dialog;
import android.app.activity;
import android.app.dialog;
import android.app.alertdialog.builder;
import android.content.dialoginterface;
import android.content.dialoginterface.onclicklistener;
import android.os.bundle;
import android.view.view;
import android.widget.button;
import android.widget.edittext;
public class alertdialog extends activity {
private edittext edittext;
private final static int dialog= 1 ;
@override
public void oncreate(bundle savedinstancestate) {
super .oncreate(savedinstancestate);
setcontentview(r.layout.main);
edittext=(edittext)findviewbyid(r.id.edittext);
button button = (button) findviewbyid(r.id.button);
button.setonclicklistener( new view.onclicklistener() {
public void onclick(view v) {
// 显示对话框
showdialog(dialog);
}
});
}
/**
* 创建单选按钮对话框
*/
@override
protected dialog oncreatedialog( int id) {
dialog dialog= null ;
switch (id) {
case dialog:
builder builder= new android.app.alertdialog.builder( this );
//设置对话框的图标
builder.seticon(r.drawable.header);
//设置对话框的标题
builder.settitle( "单选按钮对话框" );
//0: 默认第一个单选按钮被选中
builder.setsinglechoiceitems(r.array.hobby, 0 , new onclicklistener(){
public void onclick(dialoginterface dialog, int which) {
string hoddy=getresources().getstringarray(r.array.hobby)[which];
edittext.settext( "您选择了: " +hoddy);
}
});
//添加一个确定按钮
builder.setpositivebutton( " 确 定 " , new dialoginterface.onclicklistener(){
public void onclick(dialoginterface dialog, int which) {
}
});
//创建一个单选按钮对话框
dialog=builder.create();
break ;
}
return dialog;
}
}
|
运行结果:
希望本文所述对大家的android程序设计有所帮助。