Renoki: Making An Android Game (part 12)

FrameLayout with a ScrollView

My game consists of a single FrameLayout with a child SurfaceView. This essentially gives me a blank canvas to draw anything I want to, which works fine because I have a static background. What I wanted was when the user presses the “About” button, I would display the credits and the user could vertical swipe to scroll through them. At the bottom there would be an exit button. A bonus would be I could interweave images in between the credit lines, but that wasn’t necessary.

I think the typical way to do this would be to create a new activity that you create with the credits. However, I didn’t want to stop my current activity because I use a gameloop and gamestate that is local to my main activity. What I really wanted was for when the user touches the “About” button, a new ScrollView appears on top of my current SurfaceView and I change the gameState to be the ABOUT state. This is a surprisingly annoying topic to search and I had to look at a dozen posts online until I could get something to work.

First of all, you will need to create your ScrollView programmatically instead of through XML. One of the things that originally turned me off of Android was how they used XML to define the layout of the UI. I’m sure there is a good reason why they did it, but all I’ve noticed is it pisses me off and makes it harder to find the answer because most of the time people provide XML solutions. Anyway, you need to make sure your FrameLayout has an ID field so you can get a reference to it in your code.

A FrameLayout can have multiple children views, where each view will overlap the previous one.  So what I want is to create a ScrollView and add it to the FrameLayout.  A ScrollView can only have 1 child view (you can only insert 1 view into it).  Because I want to display both images and text in the scrolling area, what I did was insert a LinearLayout into the ScrollView.  Inside that Linear Layout, you can insert as many ImageViews, TextViews, etc that you want.  It will all be scrollable.

Lastly, when you want to close the ScrollView, you merely remove it from the FrameLayout. You can remove it either by passing the same View you originally created or passing the index of the View you want to remove and using removeViewAt(int ID);

The neat thing about this is if you set the size of the ScrollView to be less than the fullsize of the original SurfaceView, you can still see whatever is underneath it. TouchEvents on the non-covered sections will still trigger on the original SurfaceView, so you can reuse whatever touch logic you have from your original SurfaceView. This is how I close the ScrollView.