Android popu菜单

popu 菜单构建与contextMenu 菜单以及 optionsMenu 菜单略微不同

使用步骤为
① 创建popu 对象
② 设置监听
③ 调用popu的show() 方法

package com.example.gp11_day12_popupmenu;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;

public class MainActivity extends Activity {

private TextView textView;
private float fontSize = 20f;

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

    textView = (TextView) findViewById(R.id.textView);
    textView.setTextSize(fontSize);
}
//当点击按钮时显示弹出菜单
@SuppressLint("NewApi")
public void showMenu(View v)
{
    //创建弹出菜单
    //第二个参数接收的是一个视图对象,作用是指定弹出菜单显示的参考位置
    PopupMenu pop = new PopupMenu(this, v);
    //生成菜单项对象并加入到弹出菜单中
    getMenuInflater().inflate(R.menu.main, pop.getMenu());
    //给菜单添加事件监听
    pop.setOnMenuItemClickListener(new OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            int id = item.getItemId();
            switch(id)
            {
            case R.id.action_bigFont:
                fontSize +=5;
                textView.setTextSize(fontSize);
                break;
            case R.id.action_smallFont:
                fontSize -=5;
                textView.setTextSize(fontSize);
                break;
            case R.id.action_bgColor:
                int red = (int)(Math.random()*256);
                int green = (int)(Math.random()*256);
                int blue = (int)(Math.random()*256);

                textView.setBackgroundColor(Color.rgb(red, green, blue));
                break;
            }
            return false;
        }
    });
    //显示弹出菜单
    pop.show();

}

}

你可能感兴趣的:(android,popuMenu)