当前位置: 代码迷 >> Android >> TabHost不适用于View Pager Android
  详细解决方案

TabHost不适用于View Pager Android

热度:90   发布时间:2023-08-04 11:22:55.0

我正在按照视频创建带有导航抽屉和查看寻呼机的Tabhost,我的页面可以正常滑动,但是添加TabHost后,如果我运行我的应用程序,它将崩溃,并在此行附近给出nullpointer异常

        tabhost.addTab(tabSpac);

MainActivity.java

public class MainActivity extends ActionBarActivity implements OnPageChangeListener,OnTabChangeListener{

    ViewPager viewpager;

    TabHost tabhost;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        initViewpager();

        initTabhost();


    }



    private void initTabhost() {

        tabhost=(TabHost)findViewById(android.R.id.tabhost);
        tabhost.setup();

        String[] tabnames={"Tab1","Tab2","Tab3","Tab4","Tab5","Tab6"};

        for(int i=0;i<tabnames.length;i++)
        {
            TabHost.TabSpec tabSpac;
            tabSpac=tabhost.newTabSpec(tabnames[i]);
            tabSpac.setIndicator(tabnames[i]);
            tabSpac.setContent(new FakeContent(getApplicationContext()));
            tabhost.addTab(tabSpac);

        }

        tabhost.setOnTabChangedListener(this);
    }



    public class FakeContent implements TabContentFactory
    {
        Context context;
        public FakeContent (Context mcontext) {
            context=mcontext;
        }

        @Override
        public View createTabContent(String tag) {

            View fakeView=new View(context);
            fakeView.setMinimumHeight(0);
            fakeView.setMinimumWidth(0);
            return null;
        }

    }

    private void initViewpager() {
        viewpager=(ViewPager)findViewById(R.id.view_pager);
        List<Fragment> listFragments=new ArrayList<Fragment>();
        listFragments.add(new Fragment1());
        listFragments.add(new Fragment2());

        listFragments.add(new Fragment3());

        MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), listFragments);

        viewpager.setAdapter(myFragmentPagerAdapter);

        viewpager.setOnPageChangeListener(this);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }



    @Override
    public void onTabChanged(String tabId) {
        // TODO Auto-generated method stub
        int selectedItem=tabhost.getCurrentTab();
        viewpager.setCurrentItem(selectedItem);

        HorizontalScrollView hscroolview=(HorizontalScrollView)findViewById(R.id.h_scrool_view);
        View tabView=tabhost.getCurrentTabView();
        int scrollPos=tabView.getLeft()-(hscroolview.getWidth()-tabView.getWidth())/2;
        hscroolview.smoothScrollTo(scrollPos, 0);

    }



    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub

    }



    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub

    }



    @Override
    public void onPageSelected(int selectedItem) {
        // TODO Auto-generated method stub
        tabhost.setCurrentTab(selectedItem);

    }


}

日志

10-24 18:38:13.091:E / AndroidRuntime(13748):致命异常:主10-24 18:38:13.091:E / AndroidRuntime(13748):java.lang.RuntimeException:无法启动活动ComponentInfo {com。 example.tabhostviewpagerslidingmenu / com.example.tabhostviewpagerslidingmenu / Com.example.tabhostviewpagerslidingmenu.MainActivity}:java.lang.NullPointerException 10-24 18:38:13.091:E / AndroidRuntime(13748):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)10 -24 18:38:13.091:E / AndroidRuntime(13748):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)10-24 18:38:13.091:E / AndroidRuntime(13748):在android.app .ActivityThread.access $ 600(ActivityThread.java:128)10-24 18:38:13.091:E / AndroidRuntime(13748):at android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1161)10-24 18: 38:13.091:E / AndroidRuntime(13748):位于android.os.Handler.dispatchMessage(Handler.java:99)10-24 18:38:13.091:E / AndroidRuntime(13748):位于android.os.Looper.loop (Looper.java:137)10-24 18:38:13.091:E / AndroidRunti 我(13748):位于android.app.ActivityThread.main(ActivityThread.java:4517)10-24 18:38:13.091:E / AndroidRuntime(13748):位于java.lang.reflect.Method.invokeNative(本机方法) 10-24 18:38:13.091:E / AndroidRuntime(13748):at java.lang.reflect.Method.invoke(Method.java:511)10-24 18:38:13.091:E / AndroidRuntime(13748):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:993)10-24 18:38:13.091:E / AndroidRuntime(13748):at com.android.internal.os.ZygoteInit.main(ZygoteInit .java:760)10-24 18:38:13.091:E / AndroidRuntime(13748):在dalvik.system.NativeStart.main(本机方法)10-24 18:38:13.091:E / AndroidRuntime(13748):引起创建者:java.lang.NullPointerException 10-24 18:38:13.091:E / AndroidRuntime(13748):位于android.widget.TabHost $ FactoryContentStrategy.getContentView(TabHost.java:663)10-24 18:38:13.091:E / AndroidRuntime(13748):位于android.widget.TabHost.setCurrentTab(TabHost.java:356)10-24 18:38:13.091:E / AndroidRuntime(13748):位于android.widget.TabHost.addTab(TabH ost.java:246)10-24 18:38:13.091:E / AndroidRuntime(13748):at com.example.tabhostviewpagerslidingmenu.MainActivity.initTabhost(MainActivity.java:62)10-24 18:38:13.091:E / AndroidRuntime(13748):位于com.example.tabhostviewpagerslidingmenu.MainActivity.onCreate(MainActivity.java:42)10-24 18:38:13.091:E / AndroidRuntime(13748):位于android.app.Activity.performCreate(Activity.java :4470)10-24 18:38:13.091:E / AndroidRuntime(13748):位于android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)10-24 18:38:13.091:E / AndroidRuntime(13748):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)10-24 18:38:13.091:E / AndroidRuntime(13748):...还有11个

首先,您有一个引用集为Null,这会导致此问题发生。其次,由于描述了TabHost,请改用Material TabLayout。

这是参考代码,请尝试一下。

ublic class SimpleTabsActivity extends AppCompatActivity {

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_simple_tabs);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

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

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new OneFragment(), "ONE");
    adapter.addFragment(new TwoFragment(), "TWO");
    adapter.addFragment(new ThreeFragment(), "THREE");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}
}

这是我的XML布局。

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

  相关解决方案