Reputation: 1196
please can someone assist-
I have a popup that I have created in a function called pop that creates a popupwindow. I also have another function that when a user clicks on a button in the popupwindow, it dismisses the popupWindow. I have created a separate function for the dismissal. I would like to pass the popupwindow into the dismiss function - what is the best way to do this. I would like to reuse the dismiss function.
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void popup(View v) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.activity_alert_dialog,null);
final PopupWindow popup= new PopupWindow(layout, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
View vi=(View) findViewByID(R.id.Layout);
popup.showAtLocation(vi, 0, 20, -50);
}
public void dismiss(View v) {
popup.dismiss();
}
}
My dismiss method is executed from within a resource layout file:
<Button
android:text="cancel"
android:onClick="dismiss"/>
Upvotes: 0
Views: 97
Reputation: 669
Try this code as below: Popup will be created everytime when you call popup()
.
public class MainActivity extends AppCompatActivity {
private PopupWindow mPopup = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void popup(View v) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.activity_alert_dialog,null);
// Use global variable instead of local.
//final PopupWindow popup= new PopupWindow(layout, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mPopup= new PopupWindow(layout, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
View vi=(View) findViewByID(R.id.Layout);
mPopup.showAtLocation(vi, 0, 20, -50);
}
public void dismiss(View v) {
if (mPopup != null && mPopup.isShowing()) {
mPopup.dismiss();
}
}
}
And, I have a question about position value of mPopup.showAtLocation(vi, 0, 20, -50);
. Is it right position of y = -50
?
I think this popup will be displayed out of moniter.
Upvotes: 1
Reputation: 10959
create global variable for PopupWindow.
private PopupWindow popup;
public void popup(View v) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.activity_alert_dialog,null);
popup= new PopupWindow(layout, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
View vi=(View) findViewByID(R.id.Layout);
popup.showAtLocation(vi, 0, 20, -50);
}
public void dismiss(View v) {
popup.dismiss();
}
Upvotes: 0