Android - Prevent button click outside of PopupWin

2019-07-21 20:48发布

问题:

I've spent a while trying to get this to work, looked for similar solutions online, but none seem to work. I need my PopupWindow to only be dismissed on the click of the generate button, not by clicking outside the window. Anyone encountered this issue before?

private void LoadRAMSPopup() {
    mainLayout.getForeground().setAlpha(150);
    LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);

    final View ramsView = layoutInflater.inflate(R.layout.popup_rams, null);
    final PopupWindow popupRAMS = new PopupWindow(
            ramsView,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
    );

    if (Build.VERSION.SDK_INT >= 21) {
        popupRAMS.setElevation(5.0f);
    }

    findViewById(R.id.mainLayout).post(new Runnable() {
        @Override
        public void run() {
            popupRAMS.showAtLocation(findViewById(R.id.mainLayout), Gravity.CENTER, 0, 0);
            popupRAMS.setOutsideTouchable(false);
            popupRAMS.setFocusable(true);
            popupRAMS.update();

            Button btnGenerate = (Button) ramsView.findViewById(R.id.btnGenerate);
            btnGenerate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getApplicationContext(), CreateRAMSActivity.class);
                    startActivity(intent);
                    popupRAMS.dismiss();
                    mainLayout.getForeground().setAlpha(0);
                }
            });
        }
    });
}

回答1:

Setting up popupRAMS.setFocusable(false). removes unnecessary touch required to make popup window disappear. So please replace

popupRAMS.setFocusable(true);

with

popupRAMS.setFocusable(false);

Also try to add

popupRAMS.setOutsideTouchable(false);

Hope it will help you out.



回答2:

Use

dialog_obj.setCancelable(false)


回答3:

Try this one

popupRAMS.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(context, android.R.color.transparent)));
popupRAMS.setOutsideTouchable(false);