ActionBar PopupMenu

src/com/wind/actionbar/HelloActionBarActivity.java
package com.wind.actionbar;

import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class HelloActionBarActivity extends Activity{
    private static final String TAG = "HelloActionBarActivity";
	private ActionBar actionBar;
	protected boolean mFlagDial = false;
	PopupMenu mPopupMenu;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v(TAG, "onCreate");
        setContentView(R.layout.main);
        actionBar = getActionBar();
        //设置AcitonBar的操作模型
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);
        TextView text = new TextView(this);
        text.setTextSize(20);
        text.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
        text.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
        text.setText("I have popmenu");
        actionBar.setCustomView(text);
        text.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mPopupMenu = new PopupMenu(HelloActionBarActivity.this, v);
			    MenuInflater inflater = mPopupMenu.getMenuInflater();
			    inflater.inflate(R.menu.popmenu, mPopupMenu.getMenu());
			    mPopupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
					
					@Override
					public boolean onMenuItemClick(MenuItem item) {
						Toast toast = null;
						switch (item.getItemId()) {
						case R.id.Settings1:
							toast = Toast.makeText(HelloActionBarActivity.this,
									"Setting1 pressed", Toast.LENGTH_LONG);
							break;
						case R.id.Settings2:
							toast = Toast.makeText(HelloActionBarActivity.this,
									"Setting2 pressed", Toast.LENGTH_LONG);
							break;
						default:
							break;
						}
						
						if(toast != null){
							toast.show();
						}
						return false;
					}
				});
			    mPopupMenu.show();
				
			}
		});
    }
}

res/menu/popmenu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/Settings1" android:title="Settings1" ></item>
    <item android:id="@+id/Settings2" android:title="Settings2"></item>
</menu>

你可能感兴趣的:(ActionBar PopupMenu)