11 PopupMenu菜单和代码例子

PopupMenu 弹出式菜单 API 11以上可用

     1. 获取弹出菜单的对象
     2. 在res里的menu添加菜单项
     3. 将布局里的菜单项  给弹出菜单
     4. 进行监听弹出菜单
     5. 展示出弹出菜单

JAVA代码:

package com.fmy.popup;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
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;
import android.widget.Toast;

public class MainActivity extends Activity {

    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv);

    }

    public void click(View v) {
        //设置上下文 和锚点 
        PopupMenu menu = new PopupMenu(this, tv);
        //填充按钮
        getMenuInflater().inflate(R.menu.main,menu.getMenu());
        menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(MainActivity.this, "", 0).show();
                return false;
            }
        });
        //显示
        menu.show();
    }
}

xml menu代码:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.fmy.popup.MainActivity" >

    <item
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="我不好"/>
    <item
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="你好"/>

</menu>

效果图:
这里写图片描述

posted on 2016-09-05 20:37  木鱼哥  阅读(144)  评论(0编辑  收藏  举报

导航