Android里面主菜单里面设置菜单列表,单项选择,多项选择的实现

首先在res/menu文件下的main.xml里面设置需要的主菜单按钮:


    
    
    
    

    

然后在values/strings.xml里面抽取出对应的中文:




    主菜单选项
    Hello world!
    Settings
    菜单列表
    单项选择
    多项选择

按钮实现后如下图:Android里面主菜单里面设置菜单列表,单项选择,多项选择的实现_第1张图片

在主代码里面写实现点击后的功能,主要用AlertDialog.Builder对象,

package com.xh.tx.caidan;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		final String[] items={"转发到新浪微博","转发到QQ好友","转发到QQ空间","转发到微信"};
		if(id==R.id.list){		
			AlertDialog dialog=new AlertDialog.Builder(this).setItems(items, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					MyTask(items[which]);
					Toast.makeText(getApplicationContext(), items[which], Toast.LENGTH_SHORT).show();
				}
			}).create();
			dialog.setTitle("对话框");
			dialog.show();
		}
		if(id==R.id.single){
			AlertDialog.Builder builder=new AlertDialog.Builder(this);
			builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Toast.makeText(getApplicationContext(), "转发成功"+items[which], Toast.LENGTH_SHORT).show();
					dialog.dismiss();
				}
			});
			AlertDialog dialog=builder.create();
			dialog.show();
		}
		if(id==R.id.multi){
			AlertDialog.Builder builder=new AlertDialog.Builder(this);
			final boolean[] checkedItems={false,false,false,false};
			builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which, boolean isChecked) {
	
				}
			});
			AlertDialog dialog=builder.create();
			dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					String s="";
					for(int i=0;i
功能实现后点击按钮对应下图:

Android里面主菜单里面设置菜单列表,单项选择,多项选择的实现_第2张图片Android里面主菜单里面设置菜单列表,单项选择,多项选择的实现_第3张图片Android里面主菜单里面设置菜单列表,单项选择,多项选择的实现_第4张图片



你可能感兴趣的:(Android里面主菜单里面设置菜单列表,单项选择,多项选择的实现)