Search code examples
androidandroid-fragmentskotlinandroid-actionbarandroidx

get actionBar inside fragment using androidx


I just want to get actionBar in a fragment with a function and I am using Kotlin language and AndroidX.

this is my code:

import androidx.appcompat.app.ActionBar
import androidx.fragment.app.Fragment

class TestFragment : Fragment() {

    fun getActiobar() : ActionBar
    {
        return  activity.actionBar
    }
}

but I am getting this error:

Type mismatch: inferred type is android.app.ActionBar! but androidx.appcompat.app.ActionBar was expected.

any help?


Solution

  • The activity property of androidx.fragment.app.Fragment gives you the androidx.fragment.app.FragmentActivity "this fragment is currently associated with" (quoted from the documentation available in Android Studio)

    The actionBar property of FragmentActivity on the other hand will give you an android.app.ActionBar which is not compatible with the legacy android.support.v7.app.ActionBar or its AndroidX equivalent androidx.appcompat.app.ActionBar

    Since FragmentActivity does not have a supportActionBar property, you'll have to cast the FragmentActivity to androidx.appcompat.app.AppCompatActivity:

    import androidx.appcompat.app.ActionBar
    import androidx.appcompat.app.AppCompatActivity
    import androidx.fragment.app.Fragment
    
    class TestFragment: Fragment() {
    
        fun getActionbar() : ActionBar?
        {
            return (activity as AppCompatActivity).supportActionBar
        }
    }
    

    Note: I added the "?" because supportActionBar may be null