learner
learner

Reputation: 11790

Using ViewPager with Tabs without actionBar

I am using the google example called EffectiveNavigation to create a ViewPager with tabs. The problem is that in the manifest, for my main activity, I have set

android:theme="@android:style/Theme.Holo.NoActionBar.Fullscreen"

So that my app has no actionBar. Therefore I am getting a NullPointerException at

final ActionBar actionBar = getActionBar();//null from getActionBar()
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);//NullPointerException

Now, all I want is to be able to create a simple ViewPager with tabs. That's it. Nothing grand. I am using the google example because it is what I found. Basically in the google example, they are using the statusBar to hold the tabs. How else might I hold the tabs? Anything less than a good example or instruction on how to modify the goggle example is not going to be much help as I don't know much about ViewPagers. The link to the google example is http://developer.android.com/training/implementing-navigation/lateral.html

A simple workaround the statusBar might be enough.

Upvotes: 2

Views: 6200

Answers (3)

Fer Manza
Fer Manza

Reputation: 21

Using the ActionBar to hold the tabs is actually deprecated because, even if your app does have action bar, it may lead to NullPointerException. Good news are the TabLayout from the Design package brings you the possibility to easily create a ViewPager with tabs. Just write this in the XML of your Activity (or Fragment):

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top" />

</android.support.v4.view.ViewPager>

And once you have your Adapter for the ViewPager, include this code in the onCreate method of your Activity (or Fragment) after the setContentView method:

ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));

TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);

Hope it helps ;)

Upvotes: 2

zyzof
zyzof

Reputation: 3685

To anyone else arriving here finding that @learner's solution doesn't work for them, take a look at http://thepseudocoder.wordpress.com/2011/10/13/android-tabs-viewpager-swipe-able-tabs-ftw/

Upvotes: 0

learner
learner

Reputation: 11790

I found a fix. Basically in onCreate, before setContentView, I call

requestWindowFeature(Window.FEATURE_ACTION_BAR);

Then everything works fine.

Upvotes: 0

Related Questions