Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling setSupportActionBar in a fragment

Tags:

android

kotlin

How can I call setSupportActionBar in a fragment in kotlin language . I have a mainActivity with a navigation drawer. When I click on the first item of the navigation drawer it should opens a notesFragment . I want to set a toolBar for the notesFragment. When I tried to use AppCompatActivity().setSupportActionBar(toolbar_top) the app crashes when I click on the first item of the navigation drawer, with the error

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

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

        AppCompatActivity().setSupportActionBar(toolbar_top)
        AppCompatActivity().getSupportActionBar()!!.setDisplayShowTitleEnabled(false)
        fragments()

        AppCompatActivity().getSupportActionBar()!!.setDisplayHomeAsUpEnabled(true)

        return inflater!!.inflate(R.layout.main_fragment,null)
    }

    fun fragments() {
        var tabLayout=tab
        var viewPager=viewPager
        var adapter=viewPagerAdapterMainActivity(AppCompatActivity().supportFragmentManager)
        adapter.addFragment(firstFragment(),"first")
        adapter.addFragment(secondFragment(),"second")
        adapter.addFragment(thirdFragment(),"third")

        viewPager.adapter=adapter
        tabLayout.setupWithViewPager(viewPager)
    }

}
like image 319
Samer Sefrani Avatar asked Dec 24 '22 08:12

Samer Sefrani


1 Answers

As you're using Kotlin you can try to smart cast the activity to AppCompatActivity and then you can access the support action bar:

(activity as AppCompatActivity).supportActionBar

Note that this will only work if your host activity extends AppCompatActivity.

like image 200
Levi Moreira Avatar answered Jan 11 '23 22:01

Levi Moreira