Home > front end >  I cant set the toolbar from my fragment activity
I cant set the toolbar from my fragment activity

Time:12-04

this is code from my

HomeFragment.kt

    package com.example.mywallpaper
    
    import android.os.Bundle
    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import androidx.appcompat.app.AppCompatActivity
    import androidx.fragment.app.Fragment


    class HomeFragment : Fragment() {
    
    
    
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.fragment_home, container, false)
    
        }



        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
        //initialize action bar
            (activity as AppCompatActivity).setSupportActionBar(main_toolbar)


            val actionBar=(activity as AppCompatActivity).supportActionBar
            actionBar!!.setTitle("Fire Wallpapers")

        }

}

I am currently watching a tutorial about how to make wallpaper app even though i did everything same i have an error in (activity as AppCompatActivity).setSupportActionBar(main_toolbar) main toolbar part it says unresolved reference

<com.google.android.material.appbar.AppBarLayout
       android:id="@ id/main_app_bar"
       app:layout_constrainTop_toTopOf="parent"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintStart_toStartOf="parent"
       android:layout_width="0dp"
       android:layout_height="wrap_content">
       <androidx.appcompat.widget.Toolbar
           android:id="@ id/main_toolbar"
           android:background="@color/white"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"/>
   </com.google.android.material.appbar.AppBarLayout>

CodePudding user response:

When referencing XML resources (such as your toolbar) from Kotlin/Java code, you need to use the proper name: main_toolbar alone doesn't exist. For example, in your case the correct reference would be:

...setSupportActionBar(R.id.main_toolbar)

See more about using resources here: https://developer.android.com/guide/topics/resources/providing-resources#Accessing

There is a great guide on the App bar as well in the developer docs: https://developer.android.com/training/appbar

CodePudding user response:

to access the ActionBar from a Fragment in Kotlin:

if(activity is AppCompatActivity){
        (activity as AppCompatActivity).setSupportActionBar(main_toolbar)
    }

To set an ActionBar title from a Fragmententer code here you can do

(activity as AppCompatActivity).supportActionBar?.title = "Fire Wallpapers"

OR

(activity as AppCompatActivity).supportActionBar?.setTitle("Fire Wallpapers")
  • Related