How to implement a popup menu - Android 2.1
Popup Menu is available in Android SDK 11 on wards. Here I am implementing the concept of popup menu in SDK 7. A Button when clicked should show a Popup Menu.
In the onCreate of the main activity we have to inflate the layout of the menu which we intend to show as popup.
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
popupView = inflater.inflate(R.layout.menu_layout, null, false);
Here, menu_layout is the desired layout you wish to show as popup.
the onClick method for the button to show the popup is
the onClick method for the button to show the popup is
public void showPopup(View view) {
pw = new PopupWindow(getApplicationContext());
pw.setTouchable(true);
pw.setFocusable(true);
pw.setOutsideTouchable(true);
pw.setTouchInterceptor(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pw.dismiss();
return true;
}
return false;
}
});
pw.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
pw.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
pw.setOutsideTouchable(false);
pw.setContentView(popupView);
pw.showAsDropDown(view, 0, 0);
}
Here's the XML layout of the main activity
<?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="vertical" >
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="50dip"
android:onClick="showPopup"
android:text="@string/showPopup" />
</LinearLayout>
DOWNLOAD SAMPLE CODE