为TabLayout设置ViewPager时,空指针异常

时间:2018-07-01 21:39:06

标签: android android-fragments nullpointerexception android-viewpager android-tablayout

我有一个片段,其中包含另外两个片段,可以通过TabLayout

访问

我有以下Kotlin代码:

class TutorialFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {

        val tutorialview = inflater.inflate(R.layout.fragment_tutorial, container, false )

        tutorialview.tutorialViewPager.adapter = TutorialFragmentPagerAdapter(context!!, fragmentManager!!)

        //Null Pointer Exception on this line 
        tabBar.setupWithViewPager(tutorialview.tutorialViewPager)


        return tutorialview
    }

    companion object {
        fun newInstance() = TutorialFragment()
    }
}

我的代码因以下异常而崩溃:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.TabLayout.setupWithViewPager(android.support.v4.view.ViewPager)' on a null object reference
        at com.vedantroy.animefacekeyboard.home.tutorial.TutorialFragment.onCreateView(TutorialFragment.kt:23) 

更新1-

根据Tuby的建议,

我将代码更改为:

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {

    Log.d("KEYBOARD-APP","Inside tutorial fragment onCreate()...")
    val tutorialView = inflater.inflate(R.layout.fragment_tutorial, container, false )
    tutorialView.tutorialViewPager.adapter = TutorialFragmentPagerAdapter(fragmentManager!!)
    tutorialView.tabBar.setupWithViewPager(tutorialView.tutorialViewPager)

    return tutorialView
}

但是,尽管片段本身现在正在显示,但选项卡却没有。

2 个答案:

答案 0 :(得分:2)

错误明确指出TabLayout为空

尝试更改

tabBar.setupWithViewPager(tutorialview.tutorialViewPager)

tutorialview.tabBar.setupWithViewPager(tutorialview.tutorialViewPager)

答案 1 :(得分:0)

由于某些原因,android studio 没有自动导入顶部的库,我建议您手动导入。

将其添加为 TutorialFragment 中的顶级声明

import com.google.android.material.tabs.TabLayout