AlertDialog显示数组 类似ContextMenu效果

AlertDialog可以直接显示定义在XML中定义的数组,效果类似于在ListView上长按跳出的ContextMenu。
效果图:

实现代码:


package com.pocketdigi.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;
import android.widget.Toast;

public class main extends Activity {
    /** Called when the activity is first created. */
	Button b1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b1=(Button)findViewById(R.id.b1);
        b1.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder ad=new AlertDialog.Builder(main.this);
				final String[] itemArray=getResources().getStringArray(R.array.item);
				//获取XML文件中数组
				ad.setTitle("标题");
				ad.setItems(R.array.item, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						Toast.makeText(main.this,itemArray[which],Toast.LENGTH_LONG).show();
						//输出选中的项
					}
				});
				ad.show();
			}});
        
        
    }
}

© 2011, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记