Android - Accessing buttons from SurfaceView

2019-07-31 02:29发布

问题:

I am currently working on a simple 2d tower defense game to learn some of the basics of Android game development. To handle my graphics I have a custom object that extends SurfaceView and all of my drawing takes place on the SurfaceView's canvas object. This is all working fine.

I'd like my game to have two stages. The "combat" stage and the "building stage". In the building stage, I'm trying to add a button that can be clicked to begin the next combat stage. From my research, it sounds like buttons can't be added to a SurfaceView, but instead I should put the SurfaceView and the button(s) inside of a relative layout and align things that way. However, because I only want the button to show half of the time, I'm struggling with the best way to conditionally add/remove the button. I could hack it in there, but I'd rather take my time and do things semi-correctly if possible. Unfortunately, I haven't been able to find any good examples of this being done yet.

Is there a "best practices" way to do this, or am I missing something? Any code examples of how this can be handled would be greatly appreciated.

Thanks!

Update: I understand that I can use a layout to hold the SurfaceView and the buttons I want to display. My problem is that the buttons need to be visible only occasionally. What I need to do is set the visibility of the buttons in my parent layout from my SurfaceView object. However, this is the part that I am struggling with.

回答1:

GLSurfaceView view = new GLSurfaceView(this);
Button button = new Button(this);
setContentView(view);
addContentView(button,new  ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT ));

try this code i have placed a textview like this only and it worked



回答2:

Draw the button on the canvas as a bitmap that you overlay on the rest of the game. This gives you more flexibility in designing the look of your button and you can just have an if statement to check when the button should be drawn. Then you use a synchronized block to pull touchevents from the UI thread and check when they fall within the area of the screen where your button is.



回答3:

Add the button to the activity that holds the surfaceview. You can then set it visible/invisible by passing Messages to a handler in the thread that updates the surfaceview.

See the LunarLander example code (although that uses a textview instead of a button, iirc).