Android PopupWindow with dynamic layout September 2, 2010
Before I described how a PopupWindow in Android can be created. I used XML to describe the layout. However, sometimes the layout must change depending on various parameters. For example varying number of buttons or text boxes, or other things.
Below is an example of such dynamic layout using PopupWindow.
Public class DynamicPopup {
private Context context;
private PopupWindow pw;
// class constructor
public DynamicPopup(Context context) {
this.context = context;
}
public showPopup(int type) {
// create a LinearLayout
LinearLayout mainLayout = new LinearLayout(context);
mainLayout.setOrientation(LinearLayout.VERTICAL);
mainLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
mainLayout.setGravity(Gravity.CENTER_HORIZONTAL);
switch(type) {
case 1:
// choose the appropriate background size
mainLayout.setBackgroundResource(R.drawable.popup_background1);
pw = new PopupWindow(mainLayout, 100, 200, true);
// create a button
Button button1 = new Button(context);
button1.setText("ok");
button1.setLayoutParams(new LayoutParams(80, 35));
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View vv) {
pw.dismiss();
}
});
// add this button to the view
mainLayout.addView(button1);
Button button2 = new Button(context);
button2.setText("ok");
button2.setLayoutParams(new LayoutParams(80, 35));
mainLayout.addView(button2);
pw.showAtLocation(mainLayout, Gravity.CENTER, 0, 0);
break;
case 2:
// choose the appropriate background size
mainLayout.setBackgroundResource(R.drawable.popup_background2);
pw = new PopupWindow(mainLayout, 200, 200, true);
// create a button
Button button1 = new Button(context);
button1.setText("ok");
button1.setLayoutParams(new LayoutParams(80, 35));
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View vv) {
pw.dismiss();
}
});
// add this button to the view
mainLayout.addView(button1);
pw.showAtLocation(mainLayout, Gravity.CENTER, 0, 0);
break;
}
}
}
This is it. As simple as that.
