如何使用 Kotlin 从内部 fragment_name.kt 源文件访问 supportActionBar

How Can I access supportActionBar from Inside fragment_name.kt Source File with Kotlin

在我的 MainActivity.kt 文件中,我可以访问 supportActionBar.title 并设置标题。

TitleScreenFragment.kt 中,我无法访问:

activity.supportActionBar.title

当我尝试只使用 activity.actionBar.title 时,该值为空。

如何从我的片段代码中访问 activity.supportActionBar.title

MainActivity.kt:

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)



    val binding  = DataBindingUtil.setContentView<ActivityMainBinding>(this,
        R.layout.activity_main)

    val navController = this.findNavController(R.id.nav_host_fragment)

    NavigationUI.setupActionBarWithNavController(this, navController)

    //THIS WORKS HOW DO I ACCESS THIS FUNCTIONALITY FROM FRAGMENT CODE???
    supportActionBar?.title = "Ingredient Display"
}

override fun onSupportNavigateUp(): Boolean {
    val navController = this.findNavController(R.id.nav_host_fragment)
    return navController.navigateUp()
}

}

TitleScreenFragment.kt

    class TitleScreenFragment : Fragment() {

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

    // Setup the binding object with the layout and inflate it

    val binding = DataBindingUtil.inflate<FragTitleBinding>(inflater, R.layout.frag_title, container, false)

    // Set navigation action as an onclicklistener for button
    binding.btnBeginInput.setOnClickListener{
        view?.findNavController()?.navigate(R.id.action_titleScreenFragment_to_ingredientInputFragment)

    }

    //THIS IS NULL
    println(activity?.actionBar?.title)

    // return the inflated object in the binding

    return binding.root
    }
}

您可以使用类似的东西:

(activity as AppCompatActivity).supportActionBar?.title = "Ingredient Display"

onViewCreated 方法中(不在 onCreateView 中)。