LoginSignup
1
0

More than 3 years have passed since last update.

Navigation Architecture Componentでカスタムのhome iconを表示する方法

Posted at

Problem

Solution

MainActivity.kt
class MainActivity : AppCompatActivity() {
    private val navController get() = NavHostFragment.findNavController(nav_host_fragment)
    private val topLevelDestinationIds = setOf(R.id.homeFragment)

    // ...

    fun onFragmentViewCreated() {
        setHomeIcon(R.drawable.ic_custom_back)
    }

    private fun setHomeIcon(resourceID: Int) {
        val destinationID = navController.currentDestination?.id ?: return
        val isTopLevelDestination = (destinationID in topLevelDestinationIds)
        supportActionBar?.setDisplayHomeAsUpEnabled(isTopLevelDestination.not())
        supportActionBar?.setHomeAsUpIndicator(if (isTopLevelDestination) 0 else resourceID)
    }
}
BaseFragment.kt
abstract class BaseFragment : Fragment() {
    private val mainActivity: MainActivity? get() = (activity as? MainActivity)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mainActivity?.onFragmentViewCreated()
    }
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0