Using ViewPager with Tabs without actionBar

与世无争的帅哥 提交于 2019-12-24 01:53:58

问题


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.


回答1:


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 ;)




回答2:


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

requestWindowFeature(Window.FEATURE_ACTION_BAR);

Then everything works fine.




回答3:


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/



来源:https://stackoverflow.com/questions/22410704/using-viewpager-with-tabs-without-actionbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!