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)
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With