Close popup on Android

I have the following function that calls a popup from a menu button click. It has an ok button to close the popup. But the onclick function does not start when the button is clicked. In addition, I need to close the popup when the back button is pressed.

  LayoutInflater inflater = (LayoutInflater) MainActivity.this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); final PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.about_popup, null, false),400,440, true); pw.showAtLocation(lv, Gravity.CENTER, 0, 0); View popupView=inflater.inflate(R.layout.about_popup, null, false); Button close = (Button) popupView.findViewById(R.id.okbutton); close.setOnClickListener(new OnClickListener() { public void onClick(View popupView) { pw.dismiss(); } }); 

thanks

+4
source share
3 answers

you are currently passing another instance of View to PopupWindow and try to find the button in the difference instance using the same instance that you went through in PopupWindow to find the button. Change your code as:

  LayoutInflater inflater = (LayoutInflater) MainActivity.this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View popupView = layoutInflater.inflate(R.layout.about_popup, null, false); final PopupWindow pw = new PopupWindow(popupView,400,440, true); pw.showAtLocation(lv, Gravity.CENTER, 0, 0); Button close = (Button) popupView.findViewById(R.id.okbutton); close.setOnClickListener(new OnClickListener() { public void onClick(View popupView) { pw.dismiss(); } }); 

The second way is to use an instance of PopupWindow to find the button in the current window inside the bloat layout again for the button:

 Button close = (Button) pw.findViewById(R.id.okbutton); close.setOnClickListener(new OnClickListener() { public void onClick(View popupView) { pw.dismiss(); } }); 
+7
source
 CustomDialogClass cdd = new CustomDialogClass(this, "Internet Connection Error", "Sorry, no internet connection.Feeds cannot be refreshed", "Alert"); cdd.show(); public class CustomDialogClass extends Dialog implements android.view.View.OnClickListener { String txtTitle, txtText, txtType; Button btn; TextView alertText; ImageView imgVw; public CustomDialogClass(Context context, String title, String text, String type) { super(context); txtTitle = title; txtText = text; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.alert_layout); imgVw = (ImageView) findViewById(R.id.iconImgview); alertText = (TextView) findViewById(R.id.AlertText); alertText.setText(txtText); btn = (Button) findViewById(R.id.dismis_dialog); btn.setOnClickListener(this); } @Override public void onClick(View v) { dismiss(); } 
+1
source

Change it

  View popupView=inflater.inflate(R.layout.about_popup, null, false); Button close = (Button) popupView.findViewById(R.id.okbutton); 

to

  Button close = (Button) pw.findViewById(R.id.okbutton); 
0
source

All Articles