Here we are creating a custom contextmenu using PopupWindow in android. A simple PopUpWindow can be created using the following steps.
1)A layout XML which describes the View that will be rendered within a PopUpWindow has to be created.
2)Invoke the PopUpWindow by inflating the layout XML, and assign appropriate “parent view” to the pop-up.
Popup_example.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="10dip" android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_marginTop="10dip" android:text="Test Pop-Up"/>
</LinearLayout>
Java Code:
LayoutInflater inflater = (LayoutInflater)
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
PopupWindow pw = new PopupWindow(
inflater.inflate(R.layout.popup_example, null, false), 100, 100, true);
// The code below assumes that the root container has an id called 'main'
pw.showAtLocation(this.findViewById(R.id.main), Gravity.CENTER, 0, 0);
How to Dismiss the PopUp Window?
Declare the necessary variables:
private PopupWindow Popup;
//how much time your popup window should appear
private static final int POPUP_DISMISS_DELAY = 4000 private DismissPopup mDismissPopup = new DismissPopup();
Class for dismissing the PopUp Window
Create a class which helps in dismissing the window automatically after the specified time:
class DismissPopup implements Runnable {
public void run() {
// Protect against null-pointer exceptions
if (mPopup != null) {
mPopup.dismiss();
}
}
}
Code Snippet:
Popup = new PopupWindow(this.getViewInflate()
.inflate(R.layout.main1,null,null),0,0);
Popup.setOutsideTouchable(false);
Popup.setTouchInterceptor(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return false;
}});
Popup.showAtLocation(this.findViewById(R.id.main2),Gravity.BOTTOM, 20, 20);
youractivity.postDelayed(mDismissPopup, POPUP_DISMISS_DELAY);