Android_Menu_PopupMenu

layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击弹出PopupMenu菜单"
        android:layout_centerInParent="true"
        android:onClick="onOpenPopup"
        android:textSize="20sp"/>

</RelativeLayout>

menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/popoMenu1"
        android:title="菜单一"/>
    <item
        android:id="@+id/popoMenu2"
        android:title="菜单二"/>
</menu>

main.java

package com.example.day10_popumenu;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;
/**
 * Popupmenu 泡泡菜单,菜单放在对应的控件下面,不能自动触发
 * 1.PopuMenu在3.0以后的版本使用
 * 2.创建
 *
 * @author my
 *
 */
public class MainActivity extends Activity {

    private Button button;

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

    }
    public void onOpenPoPup(View v){
        /**
         * 创建Popupmenu对象,参数2表示将popummenu放大到对应的控件下面
         */
        PopupMenu popupMenu = new PopupMenu(MainActivity.this, button);
        //将xml的menu加载到popupMenu中
        popupMenu.getMenuInflater().inflate(R.menu.main, popupMenu.getMenu());
        //展示--点击menuitem选项后,会自动隐藏
        popupMenu.show();
        //为popupMenu 设置点击事件
        popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(MainActivity.this, item.getItemId(), 0).show();
                return true;
            }
        });
    }

}
时间: 2024-10-07 17:55:29

Android_Menu_PopupMenu的相关文章