首先在value/string.xml文件中:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">波特率选择</string>
<string name="app_name">选择</string>
<!-- 选择的内容 -->
<array name="baud_rate">
<item>B9600</item>
<item>B57600</item>
<item>B115200</item>
</array>
</resources>
在layout/main.xml中,有一个textview和button:
<TextView
android:id="@+id/myTextView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:text="波特率选择" />
<Button
android:id="@+id/myButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="100dip"
android:layout_y="30dip"
android:text="选择波特率" />
当我们按下这个按钮后,出现选择对话框,具体java代码实现如下:
public class button extends Activity {
public Button mButton1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton1 =(Button) findViewById(R.id.myButton1);
//设置按钮监听对象
mButton1.setOnClickListener(myShowAlertDialog);
}
//监听按钮按下并在按下做相应处理
Button.OnClickListener myShowAlertDialog = new Button.OnClickListener()
{
public void onClick(View arg0) {
new AlertDialog.Builder(button.this)
//设置标题
.setTitle("baudrate")
//设置选择数组和监听函数
.setItems(R.array.baud_rate, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichcountry) {
CharSequence strDialogBody = "你选择的是:";
//标签数组
String[] aryShop = getResources().getStringArray(R.array.baud_rate);
/************************选中标签后出现的对话框*****************/
new AlertDialog.Builder(button.this)
//显示 "你选择的是:"+选择的标签
.setMessage(strDialogBody + aryShop[whichcountry])
/*一般有三个Button:PositiveButton,NegativeButton,NeutralButton。
* 从名字可以看的出来,代表确定,否定,和中立,其实三个Button可以
* 写你任意的方法,只是位置上的不同而已,确定Button一般靠左,这是
* 阅读习惯。本质上都是三个Button并没有很大的区别*/
.setNeutralButton("确认", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/*在这里处理要作的事*/
}
}
)
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
).show();
/********************选中标签后的对话框到此结束*******************/
}
})
//主对话框只有一个取消键
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface d, int which) {
d.dismiss();
}
}
) .show();
}
};
}