Json zhang
Json zhang

Reputation: 129

how to use a button to control the popupwindow show or dimiss?

I want use a button to control the popupwindow, When I click the button, the popupwindow showing,and then click the button , the popupwindow dimiss. The following is my code:

@Override
public void onClick(View v) {
    showPopupWindow();
}

/*** button control the PopupWindow ***/
private void showPopupWindow() {
    View view = View.inflate(this, R.layout.popwindow_item, null);
    popupwindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    if (popupwindow.isShowing()) {  
        popupwindow.dismiss();
    }else {
        popupwindow.setOutsideTouchable(true);
        popupwindow.setBackgroundDrawable(new BitmapDrawable());
        popupwindow.showAsDropDown(title);
    }
    viewOfPop(view);
}

and the result is that when I click the button ,the popupwindow always showing,and won't dimiss. I also try to use a flag,private boolean isShow = false;,and when I click the button I will change the boolean value,but I don't kown how can I change the boolean value,the popupwindow is close when I click the outside of popupwindow. please help me ,thanks advanced!

Upvotes: 0

Views: 82

Answers (3)

Json zhang
Json zhang

Reputation: 129

I add the popupwindow.setFocusable(true); and it's ok

Upvotes: 0

Fndroid
Fndroid

Reputation: 465

mPopupWindow.setOutsideTouchable(true);

That makes your PopupWindow receive Touch Events outside of it including your Button.

When ACTION_DOWN happened, your PopupWindow will be dismissed.

When ACTION_UP happened, the Button was clicked, so go to showPopupWindow()

That why when you click the button, your PopupWindow will flicker and show forever.

Upvotes: 0

Charlie Wang
Charlie Wang

Reputation: 136

I think you are always create a new popupwindow, try to add a checking.

private void showPopupWindow() {
    if(popupwindow == null){
        View view = View.inflate(this, R.layout.popwindow_item, null);
        popupwindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    } 
    if (popupwindow.isShowing()) {  
        popupwindow.dismiss();
    }else {
        popupwindow.setOutsideTouchable(true);
        popupwindow.setBackgroundDrawable(new BitmapDrawable());
        popupwindow.showAsDropDown(title);
    }
    viewOfPop(view);
}

Upvotes: 2

Related Questions