The android tutorial USES popupwindow to create a menu example

  • 2020-05-24 06:07:59
  • OfStack

PopupWindow is a pop-up window that displays any View. It will float above the current window.

Here's the code:


public class MyActivity extends Activity{
    private PopupWindow menu;
    private LayoutInflater inflater;
    private View layout;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // instantiation PopupWindow Create a menu 
        initMenu();
    }
    // To determine key   Menu display and hide 
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(!menu.isShowing()&&keyCode == KeyEvent.KEYCODE_MENU){
           show();
        }else{
            menu.dismiss();
        }
        if(keyCode == KeyEvent.KEYCODE_BACK&&menu.isShowing()){
            menu.dismiss();
        }
        return true;
    }
    // instantiation PopupWindow Create a menu 
    private void initMenu(){
            // To obtain LayoutInflater The instance 
            inflater  = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
            // Gets the layout of the pop-up menu 
            layout = inflater.inflate(R.layout.menu,null);
            // Set up the popupWindow The layout of the 
            menu = new PopupWindow(layout, WindowManager.LayoutParams.WRAP_CONTENT,WindowManager.LayoutParams.WRAP_CONTENT);
    }
    // According to the menu 
    private void show(){
           // Set the location 
            menu.showAtLocation(this.findViewById(R.id.main), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,0,0); // Sets the display position on the screen 
    }
}

Menu layout file:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="horizontal"
        >
    <ImageView
        android:id="@+id/icon_1"
        android:background="@drawable/icon_1"
        android:layout_width="40dp"
        android:layout_height="40dp"/>
    <ImageView
        android:id="@+id/icon_2"
        android:background="@drawable/icon_2"
        android:layout_width="40dp"
        android:layout_height="40dp"/>
    <ImageView
        android:id="@+id/icon_3"
        android:background="@drawable/icon3"
        android:layout_width="40dp"
        android:layout_height="40dp"/>
    <ImageView
        android:id="@+id/icon_4"
        android:background="@drawable/icon4"
        android:layout_width="40dp"
        android:layout_height="40dp"/>
</LinearLayout>


Related articles: