Android Tab Layout with Swipeable Views

My previous article explains about Android Tab Layout and it got very good ranking in search engines. But unfortunately TabHost is deprecated by android in favor of fragments. So it is suggested that use fragment to achieve tab layout.

This article shows you how to create tab layout using fragments and viewpager. Also you can swipe between tab view as it is the functionality of viewpager which is not possible when using TabHost.

Android Material Design Tab Layout

Although this article explains the Tab Layout in well detailed manner, lot of the methods used this article were deprecated. I strongly suggest check out the latest article Android Material Design Tabs (with Android Design Support Library) once you are done through this article.

ViewPager and Fragments

Before getting into this tutorial it is suggested to have knowledge on Fragments and ViewPager as these two are main concepts used here. Unfortunately I haven’t covered about fragements and viewpager on androidhive 🙁

Layout Overview

Checkout the following pic which explains the complete overview of layout architecture. Basically we are using ViewPager as main layout and for individual pager views we use Fragments. The tabs are part of Action Bar.

Creating new Project

Even though you are not familiar with ViewPager or Fragments, don’t worry. You will get an idea about what those are and how to use them once you are done through this article. So let’s start by creating a new project.

1. Create a new project in Eclipse from File ⇒ New ⇒ Android ⇒ Application Project. While creating the project select the app theme which has Action Bar as shown in the below image.

2. As we are going to use Fragments, extend your main activity from FragmentActivity. Also implement this class from ActionBar.TabListener as we are adding Tabs too.

4. I normally prefer to create a separate package for adapter classes just to separate them from activity classes. So create a new package named your_package_name.adapter. I named my new package as info.androidhive.tabsswipe.adapter

5. I am creating a FragmentPagerAdapter class to provide views to tab fragments. Create a class called TabsPagerAdapter.java under adapter package. This adapter provides fragment views to tabs which we are going to create them later in this tutorial.

Adding Tabs to Action Bar

6. In order to display tabs we don’t have to use any other UI element like TabHost. Action bar has the inbuilt capability of adding tabs. All we have to do is enable it using setNavigationMode(ActionBar.NAVIGATION_MODE_TABS) method. Open your MainActivity.java do the following.

Here I am adding three tabs Top Rated, Games, Movies to action bar. So I just stored all the tab names in a String array and added them to action bar using a for loop.

If you run the project, you can see the tabs displaying under action bar.

Adding Views for Tabs

We already returned respected fragments for tabs in the adapter class. To make it simple I am creating very simple layout for each tab and leaving it to you to build your own UI depending on your requirement. For now I just displayed a label in the view with some background color.

» First Tab View

7. The first tab I added is Top Rated. Create a new layout file under src ⇒ res folder named fragment_top_rated.xml and paste the following code.

Run the project and check whether the views for tabs are added or not.

And this is how it looks in landscape mode

Tab Change Listener

If you run the project you can see the swiping views working, but if you select a tab, view won’t change automatically. This is because ViewPager didn’t know about the tab change event. We have to manually change the view using Tab change listener.

Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info

Just start the activity from fragment class. Place a button in fragment_games.xml and write activity launch code in GamesFragment.java and test

Vivek

Hi Ravi,

I was not specified with my question.. 🙁

Exactly what I need to know is undermentioned ::

Say I have 3 tabs –> Tab1 / Tab2 / Tab3.

Considering Tab1 –> Here I have Fragment class Say GamesFragment.java. This Fragment class have a button. Now when I click on button I need to replace fragment_games.xml with fragment_cricket.xml with it’s corresponding class CricketFragment.java.

Note* :-> This fragment_cricket.xml still exists in Tab1 … i.e. I need all tabs through out application while replacing fragments.

I will be thankful to you if you could manage your time for this. Really stuck on this.

Tom

Hi Vivek, I have the same problem than you did you find a solution?? Thanks for your help.

Vivek

Hi Tom,

If your requirement is not using an action bar tab then you can do same using Fragment and FragmentTabHost. U can do every thing with that.

for ex: U can put tab at bottom / Make your tab work with back compatibility.

I did my stuff using same and it’s working great.
Let me know if you need my help on that. I can let you get a quick start with that.

Tom

Thank you for your response.
It was not exactly my question. ^^
I want to replace on the same fragment an other fragment. I want to replace login fragment by register fragment when a button was clicked. My fragments are created dynamically and I use the replace function. The problem is when I try to do this, the login fragment is still visible. I have the feeling that the first fragment are not remove or update. I try a lot of thing that I have read on stackoverflow..but nothing work.
If U have an idea it will be help me. Thank you anyway!

Vivek

Hi Tom,

I posted comment for you over here .. But IM not finding that.
Let me know if you found that .. as IM not able to see that .

Tom

Hi Vivek, IM not able to see your comment too. Can we exchange our emails? I can’t see your mail on your profil.. Thank U for your help. Bye

Try this on onCreate method . I have tested this.. it’s working.
Let me know if any other concerns.

getActionBar().setDisplayShowHomeEnabled(false);

getActionBar().setDisplayShowTitleEnabled(false);

nirmal

so good

faraz

nice post!! nice webSite!!

Alex

Hi, can i use ListView with TopRatedFragment.java for example? findViewById is not working here.

nirmal

Hey Did u got any solution for list view
?

A

use getView()

ListView lv =(ListView)getView().findViewById(R.id.list);

Nilachandan Mohanty

Sorry for a very basic question. But how to add ViewPager from eclipse palette? I am not finding one.

Fauzi

i’m doing exactly same with this tutorial, but i have a problems with TabsPagerAdapter.java

an error occur at the fragment, and it said “Type mismatch: cannot convert from SensorFragment to Fragment”

what’s i’m missing?

Phuc Nguyen

It worked for me! Thanks so much.

Nilson Silva

Hi nice tutorial congrats…

but I have a doubt how can I put some data in the layout i.e. “Top Rated” ?

Felix

Thank you so much! Awesome Example/Tutorial.

yesid

Hello, excellent tutorial, it took me two days looking for a tutorial to serve me and this was the best.

but I have a question, as I can do so that when you turn the screen redraw is closed at this time the app to rotate the screen.

sorry for the English, is google translator

Tulai Paul

Excellent article that unravels Viewpager and tablayout. Such articles will surely inspire millions of mobile apps and games developers who have been providing with newer versions to the leading mobile ad network companies like revmob, chartboost, adcolony, appnext and others

Amit

Hi Ravi, another awesome tutorial, really helpful

May i know how to show text like this : Top Rated instead of TOP RATED

nirmal

How to add custom List View in this?? it is giving error

kevin

can i add a button in one of the tab and link to another page?

nirmal

ya
u can add button

Aleksei

This is great! Thanks a lot! You saved my day

Dan

Followed to the letter this tutorial but cannot get past step #2. I’m getting “ActionBar cannot be resolved to a type”.

I tried modifying the manifest file to select a minimum of API 11 (per the suggestion) and rebuild my project.

I’m still getting that error. Otherwise, looking forward to this tutorial as I needed such an enhancement for my project.

Manny264

Type this in within import statements: import android.app.ActionBar;
import android.app.ActionBar.Tab;

First of all a very nice tutorial. I have been following Androidhive since very long. I have created tabs as per http://www.androidhive.info/2011/08/android-tab-layout-tutorial/ Since TabActivity is deprecated from API Level 13, I want to know how can I change my code to integrate FragmentManager to achieve the same results.

Thanks for your help…

Fred

I was trying to get it from Android docs… not so clear, not so easy
Thanks a lot.

Thank you for this great tutorial. Also works flawless with ActionBarSherlock !!!

Romain

Awesome tutorial, thanks.

Eli

Great tutorial, was really helpful. How can I include a webview in the fragments instead of the textview?

Vivek

Same as U do using activity. There’s nothing change in fragment than activity else fragment provide an easy way to replace view’s.

Qt

I’ve added lists and I’m struggling with adding action listeners to the list how can i go about this?

Vivek

Specify your question what exactly U did and what exactly U require.

Lee Nguyen

Hi You,

I want to ask, for example, is rated one tab button in, press the button to move through the tab Game Sharing, which I could not get through it, and then sharing transfer functions like, thank you very much

AK

i have page with listView…but not working……Any Proper Suggestions

Kingto So

Me tooooooooo!
I’ve tried did this with ListView in each ViewPager (Tab).
But what I got was the list items didn’t respond to my touching, like out of focus.
Please help

Erando

Thanks for this tutorial. But I struggle at step 6. Everything is set as you described it, no Errors from Eclipse. But when I run the app it crashes and my logcat says: http://pastebin.com/WYTTQzAQ
NullPointer doesn’t really help a lot… do you know what could be wrong? As I sad, my MainActivity and the corresponding xml file are just as yours.

mohammadreza

nice Ravi . please teaching android server database programming. and make a example . like a Market app that working with server database.

dominic smith

nice one, i’m having trouble getting button clicks to pass from the fragment to the activity to play a sound on click. Any tips? i’ve tried the following with a “buttonPressed” tag in my xml for my fragment. but so far no good. thanks

How can I change the Fragments used in each Tab? For Example: Tab 1 has its default Fragment A. Fragment A has a button which calls Fragment B. If it is pressed, Fragment A disappears and Fragment B appears. All in the same tab.

How can this be done?

Akhila P

For each tab You ll b having a class file no??
Create an interface and in the MainActivity along with the
“implements Actionbar”.TabListener” append this too ” ClassName.Interface” followed by a comma ( , )

then Pass a reference through that interface and in that interfaces method with the help of fragment manager replace the Fragments

Naguib Ihab

Hi, I didn’t really understand the second part? Can you please explain further, or with an example? Thank you

mahdi

how can you change fragment with button call ?

ugarte

Hello! I think that the article which you have written is fantastic!
I would like to consult a doubt. I am developing an application and I have a little problem with it. How could I combine the navigation of the tabs with the navigation drawer?
I have an ActivityMain that it extend to ActionBarActivity with navigation drawable. I would like to do that if you choose a determinate Fragment, it will do a different Tabs with Swipeable Views.

Thank you very much. I wish someone has a break for answer me. Sorry, I don’t speak English very well.

As per android docs, the suggested way is not using Tabs when your app has navigation drawer. You should use only one of them.

ugarte

Thank you for your answer. I don’t found the way to do it but, It has to be possible to do it because many applications use it. For example, Google Play, Play Games, Play Books…

I divide the information with Navegation Drawer and I divide that information in categories with the Tabs.

Thank you

Mira Series

Hi Ravi,
Your web is great, keep it up !
I managed to add a webview to a fragment and to keep its state after switching fragments ( using myWebView.saveState(webViewBundle); in onpause method and restoring it )
But it’s working slow. It took like 3 seconds to switch back the fragment with the webview (Running in Atrix 2)…
I’ve been searching but i haven’t found anything about it except this http://stackoverflow.com/questions/19925776/android-webview-restore-state-pretty-slow , same problem with no answers.
Is this normal ? Do you have any suggestion?

Thanks in advance
Gabriel

Mae Lumpay

Hi. This is a great help in my project but when i run my project it stopped. Can you help me with this? Seriously im a beginner in android.

zeto

Can you make a tutorial on how to communicate between fragments and the activity?

Guest

Hi ! I’ve looked this a lot on Internet, but there’s not something as complete as this article. I’m very grateful Ravi Tamanda.

I’m new in Android Programming and I have a doubt, supose I have two buttons defined in the fragment_top_rated.xml, how can I change the layout of this Fragment (only this fragment) from TopRatedFragment.java when pressing a button?

Thanks for attention !

John Anders Murillo

Hi ! I’ve looked for this (Tabs+ Swipe Views) a lot on Internet, but there’s not something as complete as this article. I’m very grateful Ravi Tamanda !

I’m new in Android Programming and I have a doubt, supose I have two buttons defined in the fragment_top_rated.xml, how can I change the layout of this Fragment (only this fragment) from TopRatedFragment.java when pressing a button?

Thanks for attention !

SMZ

Hi, How to pass variables to tabs from MainActivity?

Donald Lee

First of all, This is the best tutorial I could find related to tabs + fragment + ViewPager, thank you so much. Just one more question to ask, how could I get the currently working fragment? I have tried several ways but seems I couldn’t get the control of the showing fragment. This may sounds a bit confusing. for instance, A non-static variable created and initialized inside fragmentA.

You can use this code to make a tab selected
actionBar.setSelectedNavigationItem(1);

hameed

Thanks Ravi ! Its work well fine ! i have a query how ca i trigger between fragment
ex : fragment A contain a button, Fragment B has some view, once i click FRAGMENT A button , i need to trigger FRAGMENT B function

Akhila P

Suppose i have tow diff listviews in two tabs say “GameList” in Games tab and “Movie List” in Movies Tab, Now the Question is How should i Start an Activity if i click a list item in the listview
i was getting an error since couldn’t get the Context and can’t start new Activity
Kindly give me how should i code the intent and initialize that…

Jake

I’m looking to use this to make a fragment activity where there are three tabs: Friends, Home, Search tabs. I would like a listview where the ViewPager is. Could this be used to do such a thing? I have something working already just without tabs and with simple buttons at the top, however tabs would be much nicer.

Haider

Very very Nice tutorial. Working absolutely perfect. Thanku very much 🙂

Erqem Husaini

Hi, Very Nice tutorial… Helped me alot
How can I have two action bar placed above one another on top of the screen with different tabs of their own.
Just simple Idea would be helpful
Thank You 🙂

Darrel Siegle

You should be able to set this android:uiOptions=”splitActionBarWhenNarrow” When the screen is narrow (portrait in a Phone) it’ll show two rows if needed, and a single row when landscape (if it fits).

If you want to always have two tab rows then you’ll need to use the TabHost and create a custom layout. I know the Author says it’s deprecated but it’s not, it’s just recommended in most cases to use the ActionBar, in support.v13 they added FragmentTabHost.

This the best tutorial anyone can have… I learned fragment and much more.. However i have few questions.. I want to support it for gingerbread api level 9, as i am using support.v4 expect it to work with api level 9.. but the action bar forcing me to use min sdk api level 14.. please help .. thank you.

Chethan Shetty

Great tutorial, can you please tell me how to capture an click event inside Games or movie tabs on text view. Thanks in advance.

Jalpesh Vrinsoft

hi thanks for such a nice tutorial but i want to know that how can i add tab host at bottom in this your sample code?
plz reply me as soon as possible

Guest

You’ll have to use the TabHost in order to have tabs at top and bottom.

sedat

Hi all
I tried to combine bottom tab host and this , although there is no error while debugging it stops can you help me?
my debug stops these lines:
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
.
.
.
Actually when I toggle these comment it works but no action tabs.

Darrel Siegle

The standard ActionBar will not allow for this, you’ll have to use TabHost to do this, not the v4 but the v13 one if you wish to support fragments.

vinayak

Hi. Thanks for this beautiful tutorial. I would like to know how to put ExpandableListView in each tabs. It would be helpful if you provide example on the same.

John

I am very new to this so I am wondering how to add list inside of one tab? Could you give me some help?

De

In the switch statement in the TabsPagerAdapter class, eclipse is not able to return the Fragment because the class is not specifically a Fragment. I have a “Type Mismatch”.

I am not able to run this on android 2.3 or high mobiles.
How can we support on android 2.3 or high mobiles.

khushwant

Hi,

You need to use android support library and also android-support-v7-appcompat to make it work.

Thanks

Krzys

Hi. Can anyone show way to send data from FragmentActivity to Fragment? I created Tab with this tutorial and now I’m trying to send String between activity and fragment.

vignesh

Hi this tutorial is very helpful. I need a suggestion that how can we change the orientation when clicking the particular tab and hide the action bar. And come back to portrait view by clicking a button.

If I run “new MyAsyncTask().execute()” in “onCreate()” (without the quotes) in main Fragment Activity, all fragments are loaded up and then execute the MyAsyncTask. I have searched on internet how to invoke a class AsyncTask before invoking onCreate, but I found nothing.

I really need your suggestion. Thanks.

Fattouh92

Great tutorial. very easy to follow

sedat

Hi this tut is very helpful for me. But I am trying to combine this with footer tab.(I have 3 tabs in footer and I wanna make one tab’s content like this), there is no error but while debugging it stops. When I looked debug way it stops when start this main. I deal 7-8 hours but I cannot found nothing. Can anybody help me?

I have a question on action bar/fragments using support library. I was trying to run this project using support library V4 and V7-appcompat and in fact was able to run this project on android 2.3. Since using support library can run action Bar and other new features on older versions, then should one always use support library to use action bar and other new features? Do you know of any disadvantage of using support library in terms of performance/crash? Also do you recommend using two sets of codes, one using support library (for API 8,9 and 10) and the other for API 11+?

Thanks,
Khushwant Singh

Guru Prasad

Hi Sir..very thankful for this tutorial ..
1)..:- i four activitys .in each activity i have list views ..now when i am trying switch activitys by swiping its taking 2 to 3 seconds to switch the activity ..what is the reason please help me..
2)..:-in 4 activitys i have constant header like master-page example (searching in listview) now where i have to write code ..i mean A , B ,C ,D are my Tabs and “Z ” is my main activity …please help me ASAP..thanks in advance

Babar

hi Guru Prasad
plz tell how you add list view in under of the tab??
i have try this i can’t..i am using display list with listadapter and arrayadapter but it will generte error sp plz help me how can iadd list view under one of tab…

RZ

Hi. thank you very much. I m newbie in Android Java. First tutorial about Action Tab that I can complete and run perfectly! Congratulations for the job.

Pablo Lunardi

Please help! Why the ActionBar is showing below the tabs when I run the app??? It should appear above , like in the video. 🙁

Micahel Panin

Hi! i am sorry for criticizing your post. It was very helpful for me. But we are inflating our view EACH time when we are scrolling through a tab. Shouldn’t we make any caching(smth like viewholder)?

Cheby

Just Perfect! Great Job

Leng AK

Hi, Sir. I have a problem in this tutorial. When I put Toast to display text in each Fragment class, it shows incorrect Toast.
How to fix it ? thx…

iloveyou

Thank you. I love you

Soheil Afshari

i have button on tab 1 how can i declare it or where should i put my codes ?

hi Leng AK
plz tell how to add list view in under of the tab??
i have try this i can’t..i am using display list with listadapter and arrayadapter but it will generte error sp plz help me how can iadd list view under one of tab…

Leng AK

hi Babar please wait, I will test it first.

Babar

ok thanks for replying Leng

Babar

Leng AK if you test it so plz tell me….

Leng AK

yes, but now i’m busy much

Babar

thanks Leng i have do but thanks

Mahdi

Hi , is it possible to change pager and tab with button event ? not with swipe

Hi, could u please help me to change “indicator color” which has been set blue as default? I want to change the tab bar indicator color to different color. Is that possible?

Hai

Hi everyone, i’d like to add a listview on each tab. Please show me how, thanks!

spiralni

Just declare it into each fragment_*.xml

spiralni

How can implement the TabListener for older devices.. It is not in the support package

Millamber

Thanks for a great tutorial, working magnificently.

I have one issue. I have a preferences activity that I use to determine which tabs will be shown which seems to work ok, but when I return to this activity, the wrong view is shown on the tab despite the adapter being updated and calling notifydatasetchanged.

Any ideas, can post code if required.

TIA

Millamber

NewBieAndroid

how to pass value from MainActivity to Fragment?
help me plsssssss

NewBieAndroid

i pass value from loginActivity to MainActivity
but, i wanna use that value each fragment
wat should i do

Dilip Kumar N

You can access the MainActivity objects from Fragment using getActivity() method

chetan

I am very new to this so I am wondering how to add list inside of one tab? Could you give me some help?

MyName

I LOVE THIS PAGE IN CAPS!

Blas

Great tutorial!

MehdiB

Awesome ! Worked like a charm 🙂 From now, I’m following your website 🙂

SP

I have 3 activities. Now I want to tab layout to show this 3 activities when I click on a one of the 3 options from the action bar. How to do that ?

Vutka Bilai

very helpful tutorial . I followed through all the tutorial . But I’m a newbie in android development , can I load listView in a fragment ACTIVITY , I mean i want to load some shared Preference data show it in a fragment view like each tab will show some data represented in a list view . can I do that in a fragment view . PLZ hepl ?

n4ssim

The tabs work well. However, how would I be able to replace the layout from a tab with a new one, say if i click on a button? Would really help if I’d know how to get this done

Vijay

Hello Ravi,
First, thank u so much for a really great tutorial for noobies like me to understand. I used your code in my mini project and am now stucked at a point. Google’d a lot but still helpless so finally have to disturb you.
what i have done is-
1.I have implemented a webview in TopRatedFragment.
2.Plz tell me how to use onKeyDown with this fragments.
3.It should be in a way that when i press back-key it should check whetther the webview can go back or else should give a alert for exiting.

Please please help!

Venubv

Hello Ravi,
Is there a way to add a bottom bar for each tab page and the bottom bar should be unique for each tab.

Regards,
Venu.

Babar

Hello Ravi,
how can i add list in under one tab??
i will try this using listadapter and array adapter but its generte error,so plz give an example in which add list in under one of tab plz…

priya

Hello Sir,
Your tutorial is very helpful.
How to add icons instead of title in tabs?
I tried with seticon() but i couldn’t figure out correctly.

Thanks&Regards,
Priya.

Commenter

My problem is after I extend fragment on some tabs than I want to use Activity which I cannot do. Because Fragment is already extended and I cannot extends Activity anymore. So what shall I do?
I after extending fragment I want to use activity also.

zeto

When you press the slide button it doesn’t do anything. What should be the code for this kind of listener?

Biraj Das

Hi

I was able to complete this project.
I am working on an App that requires to fetch data from a web service in form of json.
i followed your previous example and did that also. till here everything is fine.
Now i want to show this data on swipe of tab. this also happens but the data is shown in a different screen and you have press back to come back to the swipe able screen.
Any suggestions

I’m afraid that is not supported by the Android itself. What to you need to do?

Maykel Matheus Dias

Hi man, i’d like know how change the color of tabs…thanks

Ricardo Ferreira

Thank you very much for your solution, it solved me a huge problem 🙂

Guest

hello..i am facing a problem in TabsPagerAdapter class the error is showing… “Type mismatch: cannot convert from TopRatedFragment to Fragment” and same error in all three return type can someone help me out.

Deepak Singh

hello..i am facing a problem in TabsPagerAdapter class the error is showing… “Type mismatch: cannot convert from TopRatedFragment to Fragment” and same error in all three return type kindly help me out of this issue.

Deepak Singh

Hello Thanks a lot.. and i figured out the issue and really great article…

wiliam

how you solve it…

Antwnis

Hello. I believe there is a major bug on this project let me explain. If u add a log message on each fragment you will notice that when u select Tab1 onCreateView of Tab2 is called. Another way to chech this is to add a log message on the getItem on page adapter; one message for each new Fragment. You will notice that toprated and games are created simultaneously. Too bad i havent found what causes that mistake yet

Mike

Yes this happens to me too… Anyway I will try to find out….

Miramel

did you find the solution ?
if so plz post it

Darien

just add

viewPager.setOffscreenPageLimit(3);

Mike

well i don’t know why but i had put the line actionBar.setSelectedNavigationItem(position) in the method onPageScrollStateChanged. Then obviously i put it in onPageSelected. I don’t know if you did the same but I think that I had to mention it….Mine malakia my friend ;)…

Ann_CM++

how to send data from fragment to fragment?
help me please

Cesar M. Malainho Oliveira

It is possible to get this example to work in API 8? Thank you very much

AlexN

Yes, you must use android.support.v7.app.ActionBar.TabListener, instead of android.app.ActionBar.TabListener.

dhnjy 18

Do i need to add android support v7 library for the same reason?

Amit Kiri

Hello, I want to use this code in API 8 .But, when i run this code in API 8 I am getting these error:

I want to hide the action bar but keep the tabs, “requestWindowFeature(Window.FEATURE_NO_TITLE)” doesn’t work neither do “true” because the tabs were added to the action bar. So any solution to split them away?

Ryan

Tutorioal was great but when I swipe through the tabs the app crashes any ideas on what to fix?

there is something wrong in this code. When I pass Top Rated to Games and Games to Movies, there is no problem because each one is chosen for the first tiem(i.e. onTabSelected is called for each one)
but the problem is, when I come back to Games from Movies, or Top Rated from Games, the UI freezes. I suppose the problem is onTabReselected and onTabUnselected methods are empty. Am I right, or is there another problem?

Alex Abraham

Thank you so much!!!!!!

This really improved the UI of my application 🙂

I had a little bit of trouble adding a menu button at the top of my application once switching over to fragments but I ended up using setHasOptionsMenu(true) inside onCreate() of fragment and it worked like a charm! The menu button even disappears when swiping between activities

How can we change text size ? IS there any other option to change text font and size

Eric

Best tutorial I’ve seen on tabs. Very clean code, well organized and good naming conventions.

Ankit Aggarwal

Really nice tutorial. But I have a doubt. I had developed an app using TabHosts, it had Activities. Now when I implement ActionBar, can I use the same aCtivities instead of Fragments, as it would require a lot of change in code. If yes, then how?

Roger

Anyone else get an IllegalStateException accessing the fragments after rotating the screen using this method?

Great tutorial, I am using it in my project. Thanks for Your work. However I have a problem with replacing the fragments. How to replace any of the fragments with the new one – for example replacing the Games fragment with ‘Best adventures games” fragment. I got stucked with this. Can You please help me.

hajdi

hello. it works and it helped me a lot, but i wonder
When i turn my screen, actionBar and actionBar tabs are in the same line. Is it posible to change that so the title(action bar) will be always on top and tabs will always be on bottom? If there is a solution for that please share it with me.

Britman

This is working fine in AVD ,But not in the device ? How to fix it ?.
I used galaxy s3 for testing.
please help.

Amit Kiri

Hello, I want to use this code in API 8 .But, when i run this code in API 8 I am getting these error:

This may not help you, but maybe it will help others who want to use this functionality in lower API’s. There is a built in support library that makes it work in as low as API 7, and only requires a few changes in MainActivity.java:

something I do not understand is, like the open layout mainactivity know?

kamil

yes,
i want open new login activity, and hide tabs.
i used this:
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

but this is bad way

kamil

i want open new login activity, and hide tabs.
i used this:
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

but this is bad way, any idea how open new activity?

rags

nice tutorial .. very useful

bij

how to show the tab bar at the bottom?

smnpl

Great guide, works fine for me. One question though, which I did not solve yet myself:
I want to update data within the tab’s views, but I am not able, to access the views somehow, triggered from the activity.

My thought, on how to do that:
– The Viewpager now contains the tabs
– I tried, saving the new Fragement() in ViewPagers getItem()-method into an ArrayList, within in the ViewPager object
– From activity I can then call viePager.fragmentArray.get(index) …

– That successfully gives me a reference to the Fragment
– But on that executing getView() returns NULL … No clue what to do about that.

So, is my approach correct? If so, what am I missing? If not, what would be a proper approach?

hello, this is a particular question… how did you make the sketch for the layout it is pretty cool!

let_me_know

i want open new login activity, and hide tabs.
i used this:
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

but this is bad way, any idea how open new activity?

brian56

Hi Ravi,
You’ve made a great tutorial. But I want to work more with fragment, such as saving state of each fragment, or pressing back button to go to previous fragment.
Can you made more tutorials about fragment to provide us a typical approach to work with fragment more professionally and correctly?
Anyway, thanks for all of your tutorials, they’re really great.

Aliya

Great Tutorial, everything works fine!!! thank u so much!

Mukesh kumar

Hi Ravi,

This tutorial is very nice, but I’m getting following error.

In TabsPagerAdapter.java I’m not able to create object for my fragments ex

Could you possibly expand on this to include a list fragment in one of the tabs?

mhhra

I have a problem, after creating the 3 tabs view and each code implemented in the xml files is seen on the GUI everything is fine. But once I run the project nothing appears under each tab.

Gilbert Sarip

Thanks for the guide, but i have a button on on of the fragment, on button click it suppose to open a other “fragment”.

Is it possible to replace the current fragment with a other one
Thanks

Jose Madrid

Yes you need to call the FragmentManager and do a Replace().

Fubar

Great article — and all code does work. The only issue I had, being very new to android/java, was not understanding all the quick references that would come naturally with experience. Awesome job Ravi.

Has anybody tried this on API 9 and above…If so what are the changes.. I read the comments below there one who tried to use on Api 7 – I tried it but didn’t work. Can somebody help me out with this?

youming2007

Yes. Run on Platforms from API 7 without any problems. Changes are: ActionBarActivity (instead of FragmentActivity), getSupportActionBar (instead of getActionBar), Theme.AppCompat in AndroidManifest and of course – include support library v7 into your project (see Android documentation for more details)

Ali Bagheri Shakib

It’s so useful… Thanks a lot… 🙂
But what I should do if I don’t need the ActionBar?? I mean the tabs above, without “Entertainment” section as a bar. Just “Top Rated”, “Games” and “Movies”.

Thanks a lot…:)
I have followed this tutorial. Now i want some modification. Suppose i have a button in GamesFragment. When i press this button i want to load another Fragment in Third Tab named DetailedFragment. How can i achieve that. Pls i need this badly. Help me

hello ravi sir I have used this example but first time getItem method of FragmentPagerAdapter is being called twice ,,how to ristrict it for once…plzzzz help me…

M Luthfan Mursyidan

I follow your tutorial, but i got classnotdef exception. i read the comment below and follow the instruction to fix, but still no hope. error still appear. classnotdef appear because i deployed it to api 8.
Still no have idea to integrate your code to support api < 11. Can you point me how to fix that?

Thanks

dj-chen.com

This is helpful, but if I have a navigation drawer in the app, the tab looks bad, because when we open drawer, it can not cover the tab. Do you have any idea how to solve this?

Thanks Ravi, you had written a great tutorial. I exactly followed it.I want to transfer data from activity to fragments. I am not able to do this with bundle.(Bundle is always empty in Fragment class) Can you please help on this.

Arif YILMAZ

Hi Ravi. I implement ViewPager from your tutorial and it works. I want to change fragment inside a tab. Actually I already changed it, but there is something strange. If I go to the next tab and come back there is no problem, but if I go to the third tab and come back, the old fragment come back. May I send my code to you?

Dr Duke

Thanks a lot Ravi! really helpul and well written.

I’d like to ask you which software did you use to draw the layout overview? (it’d be the Tabs-Illustration.jpg)

Ace Rbk

Hello Ravi,I’v added an action bar up button,but when up is pressed which is supposed to go back to the last fragment,it rather loads the first homepage activity,i need to load the last fragment in tab rather.For instance,if i navigated from tab 2 to tab 3,when back is pressed,it should show tab3 fragment.

Hello @ravi8x:disqus thanks for your tutorial, I have a question, how to styling the tab style. I want to change default color so not using black and blue combination for the tab. I’ve been trying to add custom style on each fragment but the tab won’t change. thanks in advanced

Hi nice Tutorial!
Is it possible to update the TextView in the TabViews from MainActivity? I want to download data from server and then show this data in the textview in the tabviews. I want to download all data at once so I think it’s best to do this in MainActivity but i’m not able to update the textView.

Ali

Thank you!
I have been searching for a good and understandable tutorial but I couldn’t find it till I found your tutorial!

It was perfect!
Thank you so much

karimhasebou

its not working for me. there is an error in the TabsPagerAdapter
class. eclipse says The hierarchy of the type TabsPagerAdapter is inconsistent

akin

hello Ravi,

please his it possible i implement list view in each fragment? and how. please kindly assist

RB

can i place this bar at the bottom of the page?

Ahmad

Hi Ravi
How can I always show tabs below the action bar? Like in Google Play App, the tabs show below the logo in every view on all devices.
Thanks!

Alok

It’s very good tutorial. You have mentioned TabHost has been deprecated. Have they mentioned this one in Developer Android. If it is can you pls pass out the link. I read that TabActivity has been deprecated.

drup

hi..good tutorial..but when i run the program(even with your code also), I can see only action bar(Entertainment title) and rest is blank white page…no errors…where i went wrong…even i tried different emulation and changed graphical view..its same…pls suggest…..

hunterharada

hi.. i’m make tab in one activity(TabActivity), and also i’m make sliding menu using fragment, but that tab in activity before should call in one of my fragment, how can i do that? anyone can help me?

Nico

Hi. Does this solution work in Android 2.3.3? If not, what should be the alternative?

How can I prevent fragments from recreating. This approach calls onCreateView everytime i select a tab. I want to retain the previous state of the tab without recreating it.

Terrell

I dont think so, each fragment is created once. You can see it when you put a Log.v to your Switch to each case option. Then you will see that getItem() is called onetime only for each fragment, then it calls only getCount(), but you can implement FragmentStatePagerAdapter instead of FragmentPagerAdapter if you need to save state of fragment.

thank you so much,your tutorials always are goood and really help me,thanks man !!

Trent

I have a question… I’m new to Android development so I’m not sure if this is a dumb question or not. When I try to run the project it gives me an error in TabsPagerAdaptor on the line that says “return new MoviesFragment();”. It says “java:incompatible types, required android.support.v4.app.Fragment, found: com.[project name].MoviesFragment”. I at first thought this meant I need to import android.support.v4.Fragment, but I already imported that so now I’m not sure what to do. If any of you lovely people know how to fix this that would be great. Thanks!

Juan

Hi, im trying to show 4 tabs, and it makes it scrollable tabs but i want to show always the 4 tabs, what i am doing wrong? Thanks

Jorge Casariego

Thank you Ravi!!

It works perfect!

silentmind

all of hiis codes works perfectly

Nightx

Hi Ravi, the code works perfectly.. but how do i change tab text color using this method?? i want to change tab text color like into blue color..

The onCreateView() for the middle “Games” tab only gets called at start up.
The first and last tabs work fine but when you select the “Games” tab the MainActivity.onTabSelected gets the correct position (item = 1) but it then calls the MoviesFragment.onCreateView() if you are coming from the “Top Rated” 1st tab. If coming from the “Movies” 3rd tab and select the middle “Games” tab it executes the TopRatedFragment.onCreateView() method.
Anytime I select the “Games” tab, it does not execute any of the GamesFragment.java methods.
I have modeled after this code for my 4 tab application and it is preventing the middle tabs from executing the initialization code needed for those tabs.

Is there a bug in the underlying FragmentMangerImpl code?

Note: The orange “Games” layout, however, is displayed correctly and the Games tab is selected.

Bhavesh Agarwal

Can u please help me how to put the tabs at the bottom of the screen?

HO KA

Hi Ravi.
tnx, great tutorial.
I have a question: how can I add some widget to each page view that can interact with other java class that do something different in each page view?
I mean as you know we couldn’t swipe between activities so I tried to add activity to each page view. but I don’t know how.

when i swipe the tabs on create is calling twice ,,can u pls suggest the solution

Mina Gabriel

Cool what is the name of the tool you used to create the layout overview mock-up?

Aryan

Excellent tutorial but a small suggestion. The line actionBar.setHomeButtonEnabled(false); actually does no work other than increasing min API. The line requires API 14 while without this line, the code works fine on API 11 too.

Bono de Visser

In the TabsPagerAdapter make sure you import the following files:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

I let Android Studio import mine by default, but it imported different ones. When I was trying to pass getSupportFragmentManager() to the TabsPagerAdapter constructor in the MainActivity it kept complaining that I was using the wrong version. Importing the correct files will help get rid of the problem.

Pranav Lathigara

How to Change Layout or Background of Tab..?

A S

Hi Ravi, Your tutorials always give clear insight on things. Can you tell me how to make the top line bar (Action Bar) not visible to the users in THIS particular example?? I had made an app sometime back with similar code but the top line did create an issue with me… any help?

Aryan Gaikwad

@Ravi, there is a small suggestion. The tabs get focused when I slide but when I click on any tab, no action is performed. Plz update the code.

Vladimir Makarov

this method actually sucks , not the tutorial mate, no offence,you and the tutorial are rock solid, the method sucks because the action bar tabs cannot be customized easily to change its background or do other things with it, even if you find the styles for action bar and change it, there are issues with pre honeycomb and post honeycomb devices, what i rather would suggest is to have a ViewPager+TabHost with custom indicators and tab layouts that can be customized easily compared to this… 😀 but hey good one

yes I have, the custom View inside an actionbar tab has 16dp padding on all 4 sides and I havent quite figured out how to get past this 😀 thanks for the reply anyways 😀

Dinesh Babu

good Ravi

Er Krishna Gadgul

Thank You Ravi …………………….. It will helped me lot

Akshata

Thanks this did help me a lot..but i am unable to change the color of my tabs text even after lot of trial and error, hence needed some guidance regarding the same.

Vishnu

🙂

Vishnu Mohan

Thanks dude for this awesome and simple tut. You saved my day

shaki

please help me i want to add a listview with images in tab
what to do ??

anamika

nice was very helpful. may god bless you and people like you

Ali

Hi, please tell me how to instantiate buttons or use findviewbyid in MoviesFragment.java or other activities..

Syarif Ibnu Miftahudin Al-Dami

Can i hide or remove actionBar but still showing the tabs? I hide the actionBar but all tabs are hidden too.

Mark Valenzona

Thanks for this. I have a problem though in Fragments. How can I put images in a ListView in a Fragment?

Prashaant Maheshwari

Hi Ravi ,
how can i use this tabs in fragment means in my main activity i am replacing multiple fragments in a frame layout using fragment transaction so how can use this tabs inside fragment.

Richard

I have tabbed navigation for the main catagories of my app, but the activities that are called from those do not show the tabs.

Tanish

Thanks for the clear and concise tutorial. I added two methods to each of the fragments: onAttach and onResume. However i dont see the results that I am expecting. When the first tab(TopRatedFragment) gets selected..i see logs as
TopRatedFragment::onAttach…
TopRatedFragment::onResume
GamesFragment::onAttach…
GamesFragment::onResume
Then when I select Games Tab, I see
MoviesFragment::onAttach…
MoviesFragment::onResume
I never see GamesFragment onResume thereafter no matter which Tab i select ..

Could you please throw some light here?

Alan Marcel

Tamada, great tutorial! Thank you!
I just would like to say you should emphasize the AndroidManifest.xml. What do you think show this file at the end of the article?
Best regards!

k

Hi,
i implement async call in two fragment,i am on tab 3 when i move to tab 2 it call tab1,why this behavior?where i implement async call which only call one time not wach time tab change

k

not “each” time tab change

subbramanian

Hi,
Awesome article.. Thanks a lot…
Could you pls give some hints on how to add images instead of text in the tab. As tabhost is deprecated, I couldnt find any proper details anywhere for adding images.

Tianlei Hou

This is a really awesome source, thanks for the posting

bhushan

how can i add now button on any of fragment

Alireza saemi

hello android hive … y favorite tutorial site … my development home

i asked it once and u say it can be .. can we have scrollable tabs along side with navigation drawer ? i can not implement two of them because they are both fragments … this is so usefull for every one . lot of big app using this .. can u put us tutorial please ?

ireally love your site and effort ,,, your tutorial is awesome and runs even on studio … please put it in way that gradle can run it … android studio .

will be glad if u answer me can we have it or no ? tell me truth i will be grateful if you even say no

i really going to love india ppl , they are really develop passionate . thank u so much . other question is can we use this swipable tab views in android gingerbread and above ?

Alireza saemi

as always i ran this project with adt and eclipse and every thing went well :(((((
.. i really sometimes get tired of this gradle thing and what google
put us in disaster with migrate to gradle .. there are lot of conflict
.. i don’t know how to fix it to work with gradle . 🙁

Alireza saemi

………………………….

Alireza saemi

i tried that method but give me so strange error … im sry and just asking , sure u an say no to me , i have no time .. i respect you and your time .

i explained error ofcource there but my cm not moderated .. here is strange error did u saw this error before ? can u test that zip project and see it runs for you . this is my wierd error , i search alot on stack overflow but couldn’t figure out :

Hello ! Thank you so much for your guide, it’s clear and it works perfectly. I’d have just one question : I created a new ‘fragmented’ activity and I open it from the main activiy with an Intent. Is there a way to open a specific fragmentation of the activty ? For instance: I have 3 buttons in the main activity and each of them has to open a specific fragmentation. (Button1 -> Tab 1 ; Button2 -> Tab2 ..etc.. ).
Thanks in advance for any reply

myhead

I meant ‘fragment’ of the activity. My bad.

myhead

I solved it. I’ll explain for the posterity 🙂
I started a new activity in a onClick event adding some extras.

And finally I passed the value to the TabsPagerAdapter by using setSelectedNavigationItem in this way:

actionBar.setSelectedNavigationItem(variable);

Hope it’ll help someone with same ‘problem’. 🙂
See ya

Alireza saemi

any wau thank u so much man. that tutorial u give me working on eclipse . do u think i should program on eclipse and how about mke xml file on studio 😀 . until it comming to stable version

Mardoqueu

I got a problem, I’m using a in the tab “Move”, a splash screen, but when I click in “Game”, the tab Move is aclivity and a new activity open as, what much I to do to the splash screen works just when I click in Game?

dhnjy 18

Hi,,Great tutorial working fine……But how can i remove tab divider between two Tabs?

Sascha

Great Tutorial, thank you so much! Works perfect!

seetha

Ravi,

android.app.ActionBar.TabListener – This interface was deprecated in API level 21.
Action bar navigation modes are deprecated and not supported by inline toolbar action bars. Consider using other common navigation patterns instead.

But browsing at common navigation patterns don’t give any indication of how the TabSelector interface methods such as TabSelected, TabUnselected can be implemented.

Now on API 21, pls suggest what changes I should make in the code above to work. Thanks.

baskar

can anyone tell me how to customize the tab indicator(The blue strip that shows the current tab). Thanks in advance

what shld i do if i want only two tabs?
i changed the String[] tabs with two strings,
and i removed case 2 from switch in TabsPagerAdapter class,
now if i swipe the application is closing by saying “Unfortunately app has stopped working”
need help

Rohit Bandil

when i am going tab-1 to tab-3 tab is scrolling and again listView is loading in fragment. i am using ListView in fragment and attached in tab-3 .so plz give me clarity i dont want to load agian my listView in fragment that attach in tab-3.

Biswajit Jena

Hi, Thanks it’s a great tutorial. Can we set the actionbar tabs on bottom of the sceen?

Omar Ayed

how can to alignment the tabs to right not a left , this mean to start in the right

As we have 3 Tabs ,I want to validate the fields present in Tab1 and then only user should be allowed to navigate to tab2 ,and also send the data from Tab1 to tab2.

Same in case of tab2 to tab3.

I tried doing this in Main Activity where we implement TabListener interface but not able to achieve this.

Please provide the code snippet which can help me.

Manuel Sánchez

Hello I want to know what I have to do to select an starting fragment, in my app I want to in a determinate day load a position, for example, monday is 0, tuesday is 1, wednesday is 2, im not asking how to know which day is which position, just how to send that information to the fragments, tried viewpager.setcurrentitem, but no luck, thanks in advance

Hello , this is not working on android 2.3.6 version please help me. How to work in low version?

Asun VR

Thanks a lot!.
This tutorial is really great.
I would like to comment a problem I had due to the new android themes versions. This project crashes if we use “Theme.AppCompat” . The method getActionBar() in MainActivity was returning null and the app crashes, but I could resolved it changing the theme style to Theme.Holo.Light. I hope this info help somebody. Again, I would like to thank to Ravi Tamada this great site.

Yukari Yuu

Hi Asun VR…
I try this tutorial.. and like u say, it’s always crashes. I use Theme.AppCompat too. Can you tell me, how to apply Theme.Holo.Light?
because i cant change it in my style.xml

Muhammad Khalid Rahman

i just deleted android:theme=”@style/Theme.AppCompat”

from manifest file & it works 🙂

Sanya

Hell yeah, man. That’s works! Thanks a lot

Amarildo Aliaj

Hi, fantastic tutorial, but the download code button don’t work

John David

great tutorial..
can u tell me how to change the tab names (games) into images?

can i just hide “action bar tab” not action bar? i want swap able fragment like three page you have here but just not showing which one is selected.
i change setNavigationMode to standard and it crash if i swap 🙂 what can i do ?

thanks

ezaa

can u give me a specs of device on eclipse that will work on this. Thanks

Adarsha

Suppose I have to show the Movies fragment at the start of the activity, how can I declare it in the code?

Munim

Thanks for the great tutorial Ravi. Is there any way to do this using fragment instead of fragmentActivity? Thanks.

Edmhar

Are you compiling it with Navigation Drawer right?

Munim

Yes! 🙂 With navigation drawer. If you can help me out with this, that will be great. Thanks.

Edmhar

I’m also doing that and I check the net they say it can’t.

Munim

I dont think its impossible, but we have to change something. Ravi used fragmentactivity that is causing problem with navigation drawer. So one way to make it work is change to fragment or change how fragments load from navigation drawer.

Its so good but , these classes android.app.ActionBar.Tab; and tablistener are deprecated.
What we should do now ? 🙂

kuku

Nice tutorial …:)
but i want add data under these tabs ..like Google play store …
how i can do ..:(
Any One tell me please

jithea23

Great tutorial.. but i have a problem, is it possible to add FragmentActivity in the TabsPagerAdapter?

Jaideep Rawat

hi great 1..
how can we change the taskbar color??

Jose Pablo MB

Hi! Great tutorial dude!
Just one question: when i’m making the pager adapter, I get an error if I return the fragment.. The fragment class is the child of Fragment as in your example but it’s not letting me return it.
Do you know why is that?
Thanks

But I am using a Navigation Drawer too in the application.
The problem I am facing is that the Navigation Drawer should overlap the titles of the Tabs which I am unable to do as they are set in the ActionBar.

Can anyone help me to get rid of this issue??
I guess it would be done by using the PageTitleStrip. But how to implement it??

Action bar navigation modes are now deprecated in Android L ,all methods related to navigation modes in the ActionBar class (such as setNavigationMode(), addTab(), selectTab(), &c). are now deprecated.Now a Toolbar is a generalization of action bars for use within application layouts.

These methods doesn’t work in API Level 10, as you show when you create the project.

Crivi

Very good tutorial, but unfortunately as Pablo sad all the main methods are deprecated.
Can you please try to make a tutorial with an alternative solution.
Congrats for your tutorial, they are the best!

maximus

cant resolve symbol ‘FragementActivity’..Cant we use just Activity??

Tiregan

Hello,
Thanks for this nice tutarial 🙂
I am trying add something (for excample Plain text) above thses tabs and I can’t… I tried by margin but it work only for tabs content, not actionBar.
Could You help with this?

Hi 🙂 I have used above code and added list fragment in three tabs,only at the time of creation all three tabs is getting loaded,but i need to reload list on click of tab.How to do that?? can anyone help me,,

Usman

How do I reference to the objects in xml layouts?

Santosh Bhandary

how is it possibe to control auto slide inside ViewPager from a button event handling ?
I tried it using Handler with Runnable thread but all messed up .need some help guys

Pravinsingh Waghela

Thanks for the tutorial, it works great, But When I implies the Home Back(Up)navigation in Action bar it doesn’t work, can you till whats the reason? The Home Icon with back(Up) navigation symbol (“<")is available due to getActionbar().setDisplayHomeAsUpEnabled(true); but it doesn't sence any click event on it.

anusha pavan kumar

fine but it is working for one time only .
For the second time I mean in another app I am doing means UNFORTUNATELY STOPPED
I
am getting mad by trying trying. The same code it worked in one app,
copy and paste and just changed the strings even then it is not coming.
Can anyone help me to do it.

mohammed shaiban

Nice tutorial..very knowledgeable..
How can i hide the Action bar (Portion written with Entertainment) and directly show only remaining things from tabs .. because action bar place “entertainment” will be waste of place..
kindly can u help me in this, thank you

Sufiyan

Write the following line in protected void onCreate(Bundle savedInstanceState) { }code block:

in TabsPageAdapter when i write return TOPRatedF..
it gives error thar to change return type

Gaurav

When swiping from one tab to another, the app crashes. I followed the tutorial properly and checked my code a few times, but nothing seems wrong with the code. I tried removing the theme as mentioned in a comment below that too didnt work. I am using Android Studio. Please Help. Thanks.

sanjay thakur

mark break point here

viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
and see what log cat says..

pilar

I have an activity, and when I click a button, I want to start my FragmentActivity and do all this tutorial. How can I do this? Only I need to start de FragmentActivity in my OnClick(). please help!! 🙁

sanjay thakur

dont you want to tabs in your FragmentActivity or Instead to TAbs you want buttons

suniln

Sanjay Sir i have 8 buttons in one of the three tab layout.
how to go to new activity by clicking these buttons,
please help

commentsnamerequired

Unfortunately not working anymore : setnavigationmode deprecated

SANdeep Tengale

Is it a very old tutorial? Because some of the methods are deprecated..

bb

If i place a button in any one of the activity and need to access new fragment called Blackberry by clicking it , what would be the way.

What tool have you used to create mockup layout in section “Layout Overview” ? it looks cool

sak

how to disable swiping on pages? i want to swipe only through tab strip

Akshay Gangurde

Hey, Thanks for example. I’m having one issue, when I swipe on ViewPager is working perfect but when I swipe from from left to right or right to left and select previous Tab: Tab indicator appear on new selected Tab but respective fragment not appear on ViewPager.

Please help me, where I’m getting wrong?

Elie semmel

Hi

I write the same code as in the tutorial but I get the error :
“Attempt to invoke virtual method ‘void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)’ on a null object reference”

the issue is here : viewPager.setAdapter(mAdapter);
Is somebody get the same issue ? Help please

Elie semmel

resolved .

forget to change “setContentView(R.layout.activity_main);” to setContentView(R.layout.MY_ACTIVITY_LAYOUT);

Chaya Reddy

Hi…Thnq for the above static example, Can u help me to change data dynamically according to API for the same Tabs with swipe view?

Sagar Kadam

Hi..Yhank you for sharing your knowledge with us.
in my code… getActionBar() returns Null value..how I can solve it.(I already searched on google and StackOverFlow but failed to find correct ans )?

Hi. Where in the code would you put your putExtra() and get them in your fragments? Im not sure if that happens in MainActivity or in TabsPagerAdapter when you call new GamesFragment()

dara

dose it work for android 2.2? I tried it. it doesn’t work. it only work for 5.1

rakim

I have created the tabs with buttons and list views in the xml of the fragments. I cant write commands and define the function for the buttons. anytime I add onclick button functions to the fragment my app crashes before the main activity starts. please help me

Send raz

On Click of each tabs, can we reload the whole fragment of that respective tabs?? Usaually from he adjacent tab, the reloading of the fragment does not take place and I have tried and could not find a feasible solution

Wakidi Segar

Hi, nice tutorial, i have a few question, how to change the text of TextView in First Tab View dynamically?
For example, i’ve add 2 buttons in fragment_top_rated.xml. The first button will change the text of textView to “Hi, this is button 1”, and the second button will change the text of textview to “Hi, this is button 2”.

sumit

i m getting error in getSupportActionBar().setHomeButtonEnabled(false);

hey ravi i wanted to call an activity when the user swipes to game in which i wanna play youtube video so how can i do it.I used Intent for it but it’s not working

Akshay

Hi Ravi,
As we already know that ActionBarActivity is deprecated in
API 22. So Please rewrite the article without using ActionBar. Thanks in
Advance.

khannavijay

hi Ravi,
i am new to android and i would like to assign a popup menu for single tab in tablayout which was created using android design support library is it possible i refereed so many tutorials but didn’t get the solution

Hello Mr.Tamada… What should I change if I want only one tab visible at a time instead of three..

Sanchit Garg

I need to send data from the calling activity to the fragments. Normally i do that using a bundle and fragment.setArgument. As far as i understand there is a method of fragmentActivity which calls the method getItem(index) of our adapter which i need to override. can u help me please?
P.S-i love your tutorials and refer them to everyone 😀

Zafer Dean

May i know how to pass JSON data to the fragment using volley library.?

hello sir I need to change selected tab background color that mean movies TAB background color is GREEN ok so i need to set color same (GREEN) to that TAB (movie TAB)……..

so can u please help me..

Agung Nugroho

change colorAccent in values/color.xml like this
#00c853

Ervyn kaur

Hello sir, my application look exactly as in step no 6 eventough i already implement all the coding into my application as sir teach us..i can’t view or tab to another layout. I get error at in my MainActivity at the line “mAdapter = new TabsPagerAdapter(getSupportFragmentManager()); ” in getSupportFragmentManager. Sir please help me to solve..i’m doing my final year project..thank you in advance.

Vinay Mishra

Hey ravi , Suppose i have 8 buttons (when app gets launched)when i click on the 1st button the tab with swipe gesture should be launched and fragment1 should be affected (i.e. top rated should be launched) n when i click on the 2nd button again tab with swipe gestures should be launched but this time 2nd frag should be launched (i.e games should be launched) how can i get this ?
plz help me 🙂

Gokul G

hi is there possible in swipe tab in activity…

Jaideep Sah

Hi. I have created a project using Navigation Drawer Activity template of android studio.The problem I am facing is, when first time activity is getting loaded at that time 1st tab of navigation drawer menu is coming selected with default color which is blue but i want to set that color as red at the time of first time loading.anyone please help me out.your help is really appreciate for me.Thanks

Im setting text in “tab 1” after a asynctask.And its working as expected. Once switched to tab 3 and then switch back to tab 1,contents of tab reset to default text defined in xml file.So how to retain new text which is set after asynctask after swicthing between tabs.

samir

how to add check boxes for selcetion in fragment tabs

Tikam Chand Tailor

Hello! It works on FragmentActivity, but as app required i am doing this with fragment .But at

Hi, I follow this discussion to create a tab menu. But I have many problems, for example if I write: import info.androidhive.tabsswipe.R; android studio can’t resolve R. What can I do to resolve this problem?
Also the main activity.js has a lot of problems, in fact almost every string is red. Can I solve it?
I’m new in app building, so probably I don’t understand something.
Thanks a lot

manoj

if you have mistakes in xmllayout then R will be mistake.

Harsh Salot

Hi, this code works fine for me. Now I want to add login screen before mainactivity and for which I gave intent to mainactivity if successfully get login. But application shows force close error.
Please suugest me way to solve this. Thanks…..

Prateek Bihani

Showing null pointer exception on ‘actionBar.setHomeButtonEnabled(false)’, how can i resolve it, pls help me out

What is this main if you put the project, you should need to compress the file from your saved file, inside the project only contain some java file, I don’t know where to put it and details of xml files. for starter can’t able to learn.

Munish Chechi

Hello Ravi. Thanx a lot for sharing this. Your way to explain is very nice and simple.Thanx again.

David Kimigho

Hey Nice article, I have followed your implementation through out. The thing is in my fragments I always have to call getActivity() for example in toast and some times it gives a NULL POINT EXCEPTION when i am swiping through them. I have googled through and their is no clear methodology on how to handle that.
It will mean a lot if you can expound that and how to manage that

Vi Le

Hi Ravi, I have a question. How can we do validation on Tab Change Listener? If not pass the validation, stay in the current tab.

Could you please do tutorial on that ?
Including search bar like Play Store.

Hosein Saad

@ravi8x:disqus Hello Mr Tamada
I didnt know where to ask my question .
So I thought maybe you can help me.
I was going to use telegram source code(not to make an unofficial telegram messenger just to learn more)
but I coudnt
I think I should use NDK
but I dont know how to do it.
I would be so thankful if you help me.
Email : hetbo98@yahoo.com
Telegram ID : telegram.me/hetbo

JkrishnanMen

Hi Ravi,,, I am having a specific problem. I am not able to render the layout when using Swipe view inside a scroll view or vice versa. It is a known issue with android, there are many fixes recommended in Stack Overflow, but me being a rookie none of them seem to make any sense to me. Can you suggest a possible fix to this issue?

Hi, you are not taking advantage of CoordinatorLayout and NestedScrollView. Replace the top LinearLayout with CoordinatorLayout and ScrollView with NestedScrollView. Here is an example. Notice app:layout_behavior=”@string/appbar_scrolling_view_behavior” to ScrollView (or any other view that you want to display under toolbar)

JkrishnanMen

Hi Ravi,

The fix you recommended doesnt seem to work, I am attaching the code below

Hii Sir I am working on a media player app can u please tell me how can i use bind service to play music at the background and use service connection to control it from main layout activity

ami vadera

Thanx sir,now its work ,but how could i get intent data from other activity into each tabs ,and how can pass data from one tab to other activity using intent?

viji

how to shown tab1 and tab2 and make tab3 disable is this possible?

prashant dange

I got exception please help me to solve it

FATAL EXCEPTION: main
Process: com.svn.sol.myfirstfragment, PID: 4369
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.svn.sol.myfirstfragment/com.svn.sol.myfirstfragment.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setHomeButtonEnabled(boolean)’ on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setHomeButtonEnabled(boolean)’ on a null object reference
at com.svn.sol.myfirstfragment.MainActivity.onCreate(MainActivity.java:31)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Shujhal Singh

onCreate called for two tabs each time one tab is selected, data form webservice
how to solve this

Ujwal Thakre

Hii Ravi
How to implement recycler view on two tabs and simple login screen on third tab in tab view ??Is it possible to implement recycler view on fragment

Karthi9474@gmail.com

how to refresh this current Fragment like movies Fragment??

krishna

how to do i add fragment container for intent like from activity to fragment please help me out

javed

Unfortunately application has stopped plz help me anybody…

siva kumar

Hi Ravi, plz guide me .. just i want to display an aray of json Objects like each one of json obj data in one slide.. in my screen i want display only these slides, no action bar required, how can i add these slides dynamically w.r.to josn array count. Thanx in adv.

arvind koli

Hello Sir…
I learnt Very easily How to create tabs Thank U So Much….Sir..
Sir IF we want add gridview / listview / recyclerview inside tabs…then how it is possible ??
Can U help me Sir…??