如何使用OnNavigationItemSelectedListener关闭片段以查看下面的活动

时间:2019-01-06 23:48:14

标签: android android-fragments kotlin bottomnavigationview

所以创建我的应用的方式是,我有MapsActivity,它在应用启动时加载,并且我有一个底部导航小部件,带有3个图标,默认情况下在第一个图标上被选中(已命名为Map)。选中时,其他两个图标是片段。

当我单击导航小部件中的“地图”图标时,我试图关闭该片段,因为这实际上是我的主要活动。

this is what i have

现在我被困住了,因为我不知道如何关闭片段而无法回到我的MapsActivity

MapsActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_maps)
    val mapFragment = supportFragmentManager
        .findFragmentById(R.id.map) as SupportMapFragment
    mapFragment.getMapAsync(this)

    val bottomNavigation: BottomNavigationView = findViewById(R.id.bottom_navigation)
    bottomNavigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)

    getAutoCompleteSearchResults()
}

...

private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener {item->
    when(item.itemId){
        R.id.nav_map -> {
            Log.d(TAG, "map pressed")
            // if there's a fragment, close it
            return@OnNavigationItemSelectedListener true
        }
        R.id.nav_A -> {
            Log.d(TAG, "Fragment A pressed")
            replaceFragment(FragmentA())
            return@OnNavigationItemSelectedListener true
        }
        R.id.nav_B -> {
            Log.d(TAG, "Fragment B pressed")
            replaceFragment(FragmentB())
            return@OnNavigationItemSelectedListener true
        }
    }
    false
}

...

private fun replaceFragment(fragment: Fragment){
    val fragmentTransaction = supportFragmentManager.beginTransaction()

    fragmentTransaction.replace(R.id.fragmentContainer, fragment)
    fragmentTransaction.commit()
}

1 个答案:

答案 0 :(得分:1)

您可以找到当前连接的片段并将其与活动分离:

private fun detachFragment(fragment: Fragment){
val fragmentTransaction = supportFragmentManager.beginTransaction()

fragmentTransaction.detach(fragment)
fragmentTransaction.commit()
}
...

并提供一种检查可见片段的方法:

private fun getVisibleFragment(): Fragment? {
val fragmentManager = MapsActivity.getSupportFragmentManager()
val fragments = fragmentManager.getFragments()
if(fragments != null) {
    for (fragment: Fragment in fragments) {
        if (fragment != null && fragment.isVisible()) {
            return fragment
        }
    return null
    }
}
...

然后在MainActivity中使用它:

...
when(item.itemId){
    R.id.nav_map -> {
        Log.d(TAG, "map pressed")
        // if there's a fragment, close it
        val visibleFragment = getVisibleFragment()
        if(visibleFragment != null && visibleFragment.getId() != R.id.map) {
            detachFragment(visibleFragment)
        }

        return@OnNavigationItemSelectedListener true
    }
...