Popup Menu

ป๊อบอัพเมนู

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    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="com.phaisarn.jackapplication.MainActivity">

    <Button
        android:id="@+id/buttonShowPopup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="showMenu"
        android:text="Popup" />

</RelativeLayout>

menu_popup.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.phaisarn.testapplication.MainActivity">

    <item
        android:id="@+id/popup_menu1"
        android:orderInCategory="101"
        android:title="@string/popup_menu1"
        app:showAsAction="never" />

    <item
        android:id="@+id/popup_menu2"
        android:orderInCategory="101"
        android:title="@string/popup_menu2"
        app:showAsAction="never" />

</menu>

strings.xml

<resources>
    <string name="app_name">Jack Application</string>

    <string name="popup_menu1">Popup Menu1</string>
    <string name="popup_menu2">Popup Menu2</string>
</resources>

MainActivity.java

package com.phaisarn.jackapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.PopupMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

    public void showMenu(View v) {
        PopupMenu popup = new PopupMenu(this, v);
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.popup_menu1:
                        Toast.makeText(getApplicationContext(), "Popup1", Toast.LENGTH_SHORT).show();
                        return true;
                    case R.id.popup_menu2:
                        Toast.makeText(getApplicationContext(), "Popup2", Toast.LENGTH_SHORT).show();
                        return true;
                    default:
                        return false;
                }
            }
        });
        popup.inflate(R.menu.menu_popup);
        popup.show();
    }
}