Android中用兩層AlertDialog來進行彈出選擇框信息選擇
在Android經常會用到AlertDialog,把內容使用AlertDialog結合列表的形式顯示出來,然后我們點擊得到點擊的信息。 這里可以使用兩層的AlertDialog來實現
1:我們現在xml文件中定義一個要顯示內容列表數組
2:在Activity中使用 String[] items = getResources().getStringArray(R.array.item);
3:增添點擊事件,使用Alertdialog.builder 千萬不能忘了最后進行show()哦
直接看截圖的效果:
源代碼:
package com.jiangqq.alertdialog;import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button;
/**
- 使用AlertDialog進行選擇功能
- @author jiangqq
*/ public class AlertDialogActivity extends Activity { private Button btn;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.main); btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new OnClickListener() { public void onClick(View v) { final String[] items = getResources().getStringArray( R.array.item); new AlertDialog.Builder(AlertDialogActivity.this) .setTitle("請點擊選擇") .setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { new AlertDialog.Builder( AlertDialogActivity.this) .setTitle("你選擇了:" + items[which]) .setMessage("點擊選擇操作") .setPositiveButton( "確定", new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { // 這里是你點擊確定之后可以進行的操作 } }) .setNegativeButton( "取消", new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { // 這里點擊取消之后可以進行的操作 } }).show(); } }).show(); } });
} }</pre> string.xml文件內容:
<?xml version="1.0" encoding="utf-8"?> <resources>
<string name="hello">Hello World, AlertDialogActivity!</string> <string name="app_name">Hello World, AlertDialogActivity</string> <string name="btn_name">點擊彈出AlertDialog</string>
<string-array name="item">
<item>第一個選擇</item> <item>第二個選擇</item> <item>第三個選擇</item> <item>第四個選擇</item>
</string-array>
</resources></pre>轉自: http://blog.csdn.net/jiangqq781931404/article/details/7182297