PopupWindow in Android

This tutorial is about PopUpWindow in Android. Actually popupwindow came to my mind, when I need a dialog, to position at the bottom of the screen. PopupWindow is like "android.app.Dialog" only, but the main difference is in this we can position, where it need to be displayed. Not only that, now using the setElevation() (from API level 21) we can use it as a context menu. For example when long click on an view, pop up a window using PopupWindow and give the options as a list

In popupwindow also we can add a layout, much like in dialog.

The complete code is,
public class ShowPopUp extends Activity {

 PopupWindow popUp;
 LinearLayout layout;
 TextView tv;
 LayoutParams params;
 LinearLayout mainLayout;
 Button but;
 boolean click = true;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  popUp = new PopupWindow(this);
  layout = new LinearLayout(this);
  mainLayout = new LinearLayout(this);
  tv = new TextView(this);
  but = new Button(this);
  but.setText("Click Me");
  but.setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    if (click) {
     popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
     popUp.update(50, 50, 300, 80);
     click = false;
    } else {
     popUp.dismiss();
     click = true;
    }
   }

  });
  params = new LayoutParams(LayoutParams.WRAP_CONTENT,
    LayoutParams.WRAP_CONTENT);
  layout.setOrientation(LinearLayout.VERTICAL);
  tv.setText("Hi this is a sample text for popup window");
  layout.addView(tv, params);
  popUp.setContentView(layout);
  // popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
  mainLayout.addView(but, params);
  setContentView(mainLayout);
 }
}

Here, I am creating all the layout in java itself. I am not using XML for creating layout. As my current project need all the layouts in Java, I am used to create now the layout in Java itself.

The another point I want to mention is, if we put,

popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
popUp.update(50, 50, 300, 80);

this code in onCreate() wont work. So I put the code in listener of the button.

Dream Big and Work Smart To Make It a Reality !!!

Comments

Popular posts from this blog

AlarmManager and Notification in Android

Swipe Action and ViewFlipper in Android