开发者

How does a popup window on Android work if needed in non-Activity class?

I am having an issue with creating a pop-up window. I have a game i'm developing, and I'm trying to have a window or sub-menu pop up after I've won the game so the user has an option of qui开发者_运维百科tting or restarting. Everything I've seen on popup windows is done in the activity. I want to do this from my "controller" class, basically I want to check to see if the user has won within my logic class and if they did bring up a window, I have a feeling, I'm going to have to do this in my activity. Any help would be appreciated it. If you need any further details just let me know.


You will have to do it in the Activity. You have two options:

1) When you know the game is over, have a method in your "controller" class that returns whether or not the popup should be displayed. Something like isGameWon(). Call this from your Activity and respond accordingly.

2) Keep a reference to your Activity in your controller class, or allow access to your Activity as a singleton object. When the game ends, check if the player won in your controller class, and if so, call a function in your Activity to display the popup, like showGameWonPopup().

You can't display a popup outside of the UI Activity. Your two classes need to communicate about the end result of the game and respond accordingly.


You actually can show a popup from a custom non-activity class. I do it from a custom class that is set as the onTouchListener for a button in my activity. The key in this case is to get the parent of the view that is passed into the onTouch method from the activity. I think you can access the popup container view for an arbitrary class by passing your constructor the underlying activity (or the layout you used for setContentView() in that activity).

public class CustomListener implements View.OnTouchListener{

    public PopupWindow mPopup;

    public TalkButtonListener(Context ctx) {

        LayoutInflater inflater = (LayoutInflater)
            ctx.getSystemService(ctx.LAYOUT_INFLATER_SERVICE);
        mPopup = new PopupWindow(
            inflater.inflate(R.layout.popup_layout, null, false), 
            100,100,true);
    }

    public boolean onTouch (View v, MotionEvent event){

        View v2 = (View) v.getParent();

        switch(event.getActionMasked()) {
        case MotionEvent.ACTION_DOWN:
            mPopup.showAtLocation(v2, Gravity.CENTER, 0, 0);
            return(false);
        case MotionEvent.ACTION_UP:
            mPopup.dismiss();
            return(false);
        default:
            return(false);
        }
    }
}

Thanks to Todd for the code on showing the popup (here).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜