Tutorial – How To Create Swipe Views With Tabs In Android

Hello Readers

I have been making progress on my summarizer app lately. During these past couple of days I implemented a feature which lets the user swipe views as an alternative to having to tap on the tabs. This makes it more easy to swap between tabs.

Swipe between URL and Text input
Swipe between URL and Text input

Here’s How You Can Do It Too

If you’re like me, explaining something complex is facilitated by using metaphors. So I am going to do my best to explain this by making use of them.

Note:  The code I use in this tutorial can be found at developer.android. But since the explanation there is kind of dry, I will try to expand on it with my own words.

ViewPager – The Book

let’s talk about a ViewPager, one of the elements you will need in order to create swipe views. A ViewPager is like a Book. A book is nice, right? It consists of pages, which have lots of information in them.  So just keep that in mind, A ViewPager is like a book.

What is it really though? A ViewPager is a layout manager. It allows users to flip pages, which in our case are sub-activities appearing under each tab.

Let’s start by defining one in XML, create a new android XML file, name it “activity_collection_demo” and paste the following code in it:

This will be the layout used in the activity in which you want to implement your swipe views.

PagerAdapter – The Book Manager

Imagine the PagerAdapter as a person who inserts pages into a book. Without him, you would just have the book cover. He also handles in what order the pages are going to be in.

PagerAdapter is an abstract class, so we need to use one of its childs. In this case we are using FragmentStatePagerAdapter.

Fragment- The Page

We have a book, we have the person inserting pages and managing them. We just need the actual pages. Fragments are our pages. Remember how I said “sub-activities under each tab” earlier on? The correct word is fragment.

You can see it this way: A fragment is a sub-activity, usually one under each tab if there are tabs in the activity. So if you have 4 tabs in one activity, you have 4 fragments in that activity. I guess they chose to call them fragments because they are just a fragment, as in a part of an activity.

You should define an Android XML layout for each fragment, just as how you define a layout for an activity. You can also have multiple fragments using the same layout. So go ahead and define the ones you need.

Combining Everything

Now that you have the book, the book manager and the pages let me show how to combine them. The tabs are going to be added later on.

You will use three clasess, I will try to explain (remember I’m no expert at this) almost line by line so I will take one class at a time and talk about it.

Here we are creating a class called CollectionDemoActivity, which extends a FragmentActivity.  “collection” refers to a collection of fragments. You need to inherit FragmentActivity to be able to use fragments. And yes, you do need them, remember they are the pages, without them there is no shiny swiping!

Next up we define an object called mDemoCollectionPagerAdapter. This is a self made class which I will talk about later. Then we also define an object called mViewPager from the class ViewPager, you already know what this object does.

We move on to the onCreate() method of the activity. First thing we do is set the content view to the activity layout that we defined earlier on. This layout serves to tell the system that it has a viewpager. Second, we instantiate both the DemoCollectionPagerAdapter (and pass a fragmentmanager object as arguement) and the Viewpager. Lastly, we call the setAdapter method from the mViewPager object, and pass the mDemoCollectionPagerAdapter object as an arguement. This is saying that your viewpager object is going to have the mDemoCollectionPagerAdapter as it’s adapter. In other words, the book is assigning a book manager to handle his pages.

The fragmentmanager we passed as an arguement to the pageradapter is an object that belongs to the FragmentActivity class. Since we are extending our class to a FragmentActivity, we can make use of FragmentManager.

Let’s move on.

This public class DemoCollectionPagerAdapter extends the FragmentStatePagerAdapter class. You have to implement your own class as FragmentStatePagerAdapater is abstract. You can name it what you want, it represents the The Book Manager (PagerAdapter).

The first method just passes the fragmentmanager on to its superclass.

The second method, getItem, gets the fragment (the page) that you want. This is done by first instantiating the fragment object from another nested class we will define later on. Next an integer is added as an arguement to the fragment, what this will do is show the number of the fragment. Imagine there’s 10 fragments in your activity, then when choosing tab number 8, that number will appear once you call that fragment.

The third method, getCount, just returns the number of fragments that the activity has. This is where you choose how many fragments you want.

The fourth method is just an automatic title creator for each fragment on your activity. For example the title for the 4th fragment would be OBJECT 4.

Moving on.

This class represents the Pages, or the Fragments. Again, you can call it what you want, but it must extend the Fragment class, which is also an abstract class.

This fragment object only has one method which does a couple of things. First, it inflates a layout, which you can define to look however you want and stores it in a view called rootView. Second, it gets a textview via rootView and sets its text to the number of the fragment. This number is sent through the arguments (ARG_OBJECT) we defined earlier in DemoCollectionPagerAdapter. Lastly, it returns rootView.

Note:  Right now we just defined one fragment, this means that it doesn’t matter how many fragments your activity has, it can only implement the one fragment we defined. to add more fragments and use different layouts, just create another class and extend Fragment, and assign a different layout to it.

That’s how you combine the three players: The Book, The Book Manager and The Page. But we are not finished yet, we are missing the tabs and also the whole purpose of this tutorial: the swiping!

Implementing Tabs and Swiping to our Demo

Let’s jump into the code for adding tabs first:

This code goes inside the onCreate() method of the first class we created: CollectionDemoActivity.

First we get the activities’ actionbar by calling getActionBar() and assign that to the variable actionBar.

By calling the method setNavigationMode and passing NAVIGATION_MODE_TAB we are telling the system that we are going to use tabs in order to navigate through our activity.

Next, we create a tab listener which then implements three methods. They listen to whenever the user selects, reselects or unselects a tab. Add code accordingly if you want something to happen when navigating through tabs. In the code shown above, whenever the user selects a tab, we tell the viewpager (the book) to show a specific fragment with the method setCurrentItem(tab.getPosition()).

Note: This tab listener doesn’t listen to swipes. We are going to create another listener that will listen to swipes in a few moments.

We then create three tabs. We iterate until mDemoCollectionPagerAdapter.getCount() because that’s where we know how many tabs we want. Inside each iteration we define the page title by calling the getPageTitle() method. Finally, we set the listener to the tabs we created. If you use “this” instead of “tabListener” then your activity will implement the ActionBar.TabListener interface instead of the object tabListener that we just defined.

Last of all, and most important of all, because this is what we were waiting for, is the swipe listener. It’s called a SimpleOnPageListener and it does what it says, listen to the “pages” (fragments). We start by getting our mViewPager object and calling setOnPageChangeListener. As an arguement we implement the SimpleOnPageListener interface and override its onPageSelected method to call setNavigationItem() and set the specific tab that we want whenever we swipe.

And that does it, with that listener in place, you will be able to swipe between your fragments.

Closing

I have shown you how to implement the swipe feature by using the code found on developer.android. It was really hard to read through that page because of the lack of explanation, so I hope that by writing this I cleared out some of your doubts.

If you tried to implement this and it didn’t work, don’t hesitate to ask me. What I did to implement this feature was follow the various tutorials out there by other people like me.

Note: If you see something wrong, please do comment so I can correct it!

It would be great if you tried out the app where I implemented swipe views and told me what you think!
Link to App: Click Here

If you like, you can sign up to my mailing list and receive an e-mail notification whenever I bring out new content. No spam! I promise :)
[wp_email_capture_form]

 

Day 16 & 17 – Learning Android Development

Day 16

I spent the whole day finishing star-assault. The idea was to implement what was missing from the tutorial. On day 15 I had implemented turning and collision detection between bob and blocks. In total, what follows was what I added to the game:

Gravity: Bob now falls down at a constant speed if there’s no blocks beneath him and stops when there are.

Jumping: now bob can jump whenever space is pressed or the lower-center part of the android device is touched. He jumps at a constant speed, and can keep hovering in the air, so it’s basically flying but whatever.

Pigs: The enemy, they have simple AI where they just stand in place and turn and shoot left if bobs left of them and shoot right if bob’s right of them. They have 10 points of health, one bullet takes down 1 point of health. If the health reaches 0 they die.

Humanoid Pig
Dead Pig

 

 

 

 

 

 

 

 

Bullets: bullets comes out automatically from bob and the pigs, I didn’t opt for touch to shoot because the player already has to touch the screen for walking and jumping.

bullet

Collision: Between bob and pigs, between bullets and bob, between bullets and pigs, between bullets and blocks.

Level: I added another level, as in another window like the original but with rearranged blocks, with a pig in it. I could have done more “levels” but I wanted to finish this game.

Health: Three little hearts represent bob’s health, one bullet hit is one heart.

Win and Lose: When you kill the second pig and walk to his spot, a win screen appears. when you lose your health, a lose screen appears.

Here’s a short video of the whole game:

[youtube http://www.youtube.com/watch?v=t2qODmLsTpM]

I ran across a few problems during the development. One was that on my android device, I could only pass the game once, and when I closed and opened the app, the win screen would still be there, even though I was at the starting spot again. After searching I realized it was the static variables that persisted even though the app was destroyed, so i changed them into public instead.

I call the main activity on the onStart() method for android and not on the onCreate() because I want the game to restart every time you go away from the activity.

Day 17

I designed an icon for the app, a quick google taught me some of the basics but I didn’t spend much time on it.

 

 

 

 

 

 

Then I wanted to see if I could publish it (for free of course) on the Google playstore, just to see the process.Turns out I need to create a developer profile, and then pay 25$ via google checkout, which you need a credit card for, and I don’t have one. I’ve been avoiding a credit card for years but I guess I’ll have to get one in order to reach my 30 day goal of publishing an app.

I don’t consider this to be my first app, as the base of the code is not mine even though it’s open source. I want my first app to be all mine, I know I’m going to use some of the code from the tutorial as I will be using libgdx as well, but it will be for building an entirely different game.

The Game:

Desktop version, Android version, Source code (only includes the classes).

credits go to Tamas Jano for the tutorial, and I’ll take credits for what I added :)

Day 14 – Learning Android Development

Today I reviewed the tutorial  from yesterday. I started adding little stuff to the game, all by myself. I can’t believe how much more I learned by trying to add stuff to the game, than actually reading the tutorial line by line or re-doing it. When you want to add something by yourself, you have to find a way to do it, and you search and try until you can. It’s trial and error. Of course you need to first take a look at all the clases and see how they’re connected to each other and have a little background knowledge on how the game was built. Not to forget you have to know some java as well. But as I said, after all that, the best way to keep improving is implementing stuff yourself.

Here’s how the game has evolved visually. The images are from the PC version, but the same goes for the android version, both use the same source.

[slideshow]

Bob has now become bigger and is a kind of space trooper. The blocks are now some type of concrete, and there’s a space themed background. Some quick photoshop did the work, I find it really great for pixel art.

On the technical front, the game has evolved as well. Now you Bob turns right and left, so he doesn’t only see on one direction anymore. I spent a great deal of time figuring out the collision detection’s parameters with bob and the blocks.  I know one of the ways you do it is by setting up a big if-statement within a loop traversing the blocks, the if-statement will return true when one block is near and then you make bob’s speed zero and he can only go to the opposite direction. What i took time with was finding the right numbers, how far should bob stop from the blocks, etc. Plus I had a bug where he would magically appear next to the block he was being blocked at, very cool.

I probably added some other minor things I don’t quite recall at the moment. I want to keep working on this game for a bit, mess around with it to see if I can implement jumping, more  levels, AI, shooting. Definetly gravity, because right now he just walks at a height of 2 units, whether there’s a block or not.

I really like the MVC style, you separate the models (Bob,world,blocks), the view(rendering) and the controller(input/event handler) in different classes. Makes things more organized.

Day 12 and 13 – Learning Android Development

I decided to start with game development on android. I will use a free library called libgdx and follow a tutorial on making a little 2D game with it. libgdx is a java library that allows its users to create games on their desktop and then deploy it to Android. The author of the tutorial says that it is based on OpenGL, but you don’t touch the OpenGL yourself,  like in pygame. You let libgdx deal with the complex stuff while you focus on the actual game. Sounds like something good right now, as I want to publish my first app in a short time.

The Tutorial

Everything that follows is what I did by following the tutorial which is linked on the paragraph above. The author is Tamas Jano, all credits for this game go to him. Here is the game’s source. The game is based off another game called Star Guard.

I started off by installing libgdx and by creating three projects, star-assault, the main project, and star-assault-android along with star-assault-desktop. The last two serve as launchers for the two platforms. Then i added the libgdx JARS into their corresponding build paths within the project so I can use/implement the methods.

After the setting up, I started with the game. I created the game class StarAssault and then implemented the interface ApplicationListener. Which has the core methods create(), resize(), render(), pause(), resume(), dispose(). Most of them correspond to the app lifecycle phases. The render() method is the heart of the game, there is where I put the main loop and resize() id when the screen dimensions are changed.

After just implementing the methods without filling them up, the player class which is called Bob is created. The game is 2D tile based, so 1 block is 1 unit of height and 1 unit of width. Bob is 1/2 unit tall. Bob has several attributes, like a position in the world, acceleration when jumping, velocity when moving, etc. Bob will be running at 2.7 units per second. Because a running speed of 10km/h is 2.7 meters per second, and 1 meter = 1 unit.

Then follow the Block class, which is another actor just like Bob. Blocks  have some attributes as well, a position, bounds so that nothing penetrates them and sizeBoth Bob and Block use a vector class from libgdx for the position, this helps because it provides help with position, velocity, collition etc.

Next is the World class, which is a container class for Bob and Block. An array is created for several instantiated Blocks and Bob is of course uniquely instantiated unless I want more Bobs around.

To render the world, a screen is needed, so I created the class GameScreen . Screen is an interface from libgdx, I implement that to the GameScreen class. The Game class from libgdx has tools that are needed so I extended the StarAssault class with Game. Gamescreen is then called/instantiated under StarAssault.

StarAssault will use the create() method, which will instantiate a GameScreen object. The GameScreen object will then use the show() method and subsequently the render() method for every cycle. So the game loop will be situated in the GameScreen class.

What follows is the WorldRenderer class, this one get’s instantiated under the show() method in GameScreen . Then under the GameScreen’s render() method, the method render() from WorldRenderer gets invoked. WorlRenderer.render()  gets all the information from the world and its actors and renders them.

After setting up the renderer, the positions, without setting up an event handler, or proper images, and setting up the desktop launcher, I got this:

Desktop Launcher
on my Samsung Galaxy SII

The blocks are wider on my phone because I used a dimension of 480×320 for the desktop version, which is apparently not the same ratio as the Samsung’s.

Remember I said height and width were the same? well, only for the engine, not visually. The engine is told to render a screen equivalent to 10×7 blocks and each block measures 1(unit). But it is also told to fill out the screen and so the width of the blocks are visually bigger, because a phone’s horizontal view has a wide aspect. And so when an image is inserted, it will be distorted by OpenGL in order to fill out the screen.

With the Textures
On the SII

I made the block 20×20 pixels and Bob 6×10. On the desktop, the resolution of the window is 480×320, so that means each block should have a width of 48 so each pixel matches the screen pixels, but there’s only 20 pixels in the width of each block, so that means the image gets distorted (it gets wider) to fill out. Doesn’t really matter for this game though.

for the event handling, I created a new package and in it the class WorldController. The class is able to handle both touch input for android and key input for the PC. Bob is able to move now, but only horizontally.

Conclusion

This is as far as the tutorial goes, a second part was promised where the game would be completed with features like terrain interaction, animations, sounds, AI, etc. but seeing as the post was released on February 2012, I doubt a second part will ever come. Nonetheless this was a great tutorial and I will probably take another look at how this game was made again step by step. I liked the library too. Thanks Tamas.

Day 11 – Learning Android Development

The tutorials on game programming in java from TheNewBoston didn’t go as smooth as I thought. As a result I was only able to see the first 12 tutorials. Setting up a simple animation loop is very complex compared to the pygame library in python. This is why it’s probably better to make games in Java over python. It’s less automated and you have more freedom to set up your settings,and your game is probably less bloated, although at a cost of a higher learning curve.

Today I saw a bit more about threads, how to set up the screen for games, how to load images and the beginnings of animations. I also learned what a synchronized methods is. I didn’t even get to an event handler.

I will stop with these series for now. They teach you game development, which is something I want to learn, but for android. I should’ve looked before, but only now do I realize that the library used for Java pc games in the video series is not the same as for android. But hey I at least I got an introduction if I ever want to start making pc games in Java.

So tomorrow I go back to android development as planned, I will pick up where I left on the video tutorials from TheNewBoston. I will eventually also search for tutorials on android game development. A quick google search showed me the android.graphics library, which is probably the way into game dev, I will look further into it.