本文实例讲述了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>
|
alertactivity类
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
59
60
61
62
63
64
65
|
package com.ljq.dialog;
import android.app.activity;
import android.app.dialog;
import android.app.alertdialog.builder;
import android.content.dialoginterface;
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 ;
boolean [] flags= new boolean []{ false , false , false }; //初始复选情况
string[] items= null ;
@override
public void oncreate(bundle savedinstancestate) {
super .oncreate(savedinstancestate);
setcontentview(r.layout.main);
items=getresources().getstringarray(r.array.hobby);
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( "复选框对话框" );
builder.setmultichoiceitems(r.array.hobby, flags, new dialoginterface.onmultichoiceclicklistener(){
public void onclick(dialoginterface dialog, int which, boolean ischecked) {
flags[which]=ischecked;
string result = "您选择了:" ;
for ( int i = 0 ; i < flags.length; i++) {
if (flags[i]){
result=result+items[i]+ "、" ;
}
}
edittext.settext(result.substring( 0 , result.length()- 1 ));
}
});
//添加一个确定按钮
builder.setpositivebutton( " 确 定 " , new dialoginterface.onclicklistener(){
public void onclick(dialoginterface dialog, int which) {
}
});
//创建一个复选框对话框
dialog=builder.create();
break ;
}
return dialog;
}
}
|
运行结果:
希望本文所述对大家的android程序设计有所帮助。