0

I have an app build with Fragments. The problem is the Activity uses the Fragment class name for its title instead of the title I set. Some parts of the code that can be useful:

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)

        topAppBar = binding.topAppBar
        setSupportActionBar(topAppBar)

        val navHostController = supportFragmentManager.findFragmentById(R.id.detailFragment)
        val navController = navHostController?.findNavController()
        if (navController != null) {
            NavigationUI.setupActionBarWithNavController(this, navController)
        }
    }

}

DetailFragment.kt

class DetailFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        // Also tried in onCreateView and onCreateOptionsMenu
        requireNotNull(this.activity).title = getString(R.string.app_name)
        ...
    }
}

Any ideas?

  • 1
    You'll find a few solutions to this problem here: https://stackoverflow.com/questions/52511136/how-to-set-title-in-app-bar-with-navigation-architecture-component – Gavin Wright Aug 28 '20 at 16:34
  • Thanks! I couldn't find that question. Back to the answer, is it possible to set the title using only the android:label property, so no code is required? – Manuel Alcaraz Aug 28 '20 at 18:49

0 Answers0