Friday, 21 April 2017

How to create a popup window (PopupWindow) in Android




To create a simple working PopupWindow, we need to do the following:



popup_example.xml:




android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"

android:layout_height="wrap_content">

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="Test Pop-Up" />





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);

pw.showAtLocation(this.findViewById(R.id.main), Gravity.CENTER, 0, 0);



My requirement is that I need a






and a






in my popup_example.xml. How can I handle these two components in my Java code?



screenshot


Answer



Here , I am giving you a demo example . See this and customize it according to your need.



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);
}
}



Hope this will solve your issue.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...