package com.js.sinlgechoiceitemstest; java
import android.app.Activity; android
import android.app.AlertDialog; 數組
import android.content.DialogInterface; app
import android.os.Bundle; ide
import android.os.Handler; post
import android.view.View; ui
import android.view.View.OnClickListener; this
import android.widget.Button; url
import android.widget.Toast; spa
publicclass SingleChoiceItemsTest extends Activityimplements OnClickListener
{
private String[] province = new String[] { "上海", "北京", "湖南", "湖北", "海南" };
private Button btnSingleChoiceList;
// 單擊事件對象的實例
private ButtonOnClick buttonOnClick = new ButtonOnClick(1);
/** Called when the activity is first created. */
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnSingleChoiceList = (Button) findViewById(R.id.btnSingleChoice);
btnSingleChoiceList.setOnClickListener(this);
}
@Override
publicvoid onClick(View v)
{
showSingleChoiceButton();
}
// 在單選選項中顯示 肯定和取消按鈕
//buttonOnClickg變量的數據類型是ButtonOnClick,一個單擊事件類
privatevoid showSingleChoiceButton()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("請選擇省份");
builder.setSingleChoiceItems(province, 0, buttonOnClick);
builder.setPositiveButton("肯定", buttonOnClick);
builder.setNegativeButton("取消", buttonOnClick);
builder.show();
}
privateclass ButtonOnClick implements DialogInterface.OnClickListener
{
privateint index; // 表示選項的索引
public ButtonOnClick(int index)
{
this.index = index;
}
@Override
publicvoid onClick(DialogInterface dialog,int which)
{
// which表示單擊的按鈕索引,全部的選項索引都是大於0,按鈕索引都是小於0的。
if (which >= 0)
{
//若是單擊的是列表項,將當前列表項的索引保存在index中。
//若是想單擊列表項後關閉對話框,可在此處調用dialog.cancel()
//或是用dialog.dismiss()方法。
index = which;
}
else
{
//用戶單擊的是【肯定】按鈕
if (which == DialogInterface.BUTTON_POSITIVE)
{
//顯示用戶選擇的是第幾個列表項。
final AlertDialog ad = new AlertDialog.Builder(
SingleChoiceItemsTest.this).setMessage(
"你選擇的地區是:" + index + ":" + province[index]).show();
//五秒鐘後自動關閉。
Handler hander = new Handler();
Runnable runnable = new Runnable()
{
@Override
publicvoid run()
{
ad.dismiss();
}
};
hander.postDelayed(runnable, 5 * 1000);
}
//用戶單擊的是【取消】按鈕
elseif (which == DialogInterface.BUTTON_NEGATIVE)
{
Toast.makeText(SingleChoiceItemsTest.this, "你沒有選擇任何東西",
Toast.LENGTH_LONG);
}
}
}
}
}