Android replace the current fragment with another fragment

前端 未结 6 1337
迷失自我
迷失自我 2020-11-28 09:23

I just started with fragment design for HoneyComb. I created two fragments. When i click a button in the left side fragment, a new fragment is created in right side. Meanwh

6条回答
  •  情书的邮戳
    2020-11-28 09:48

    If you have a handle to an existing fragment you can just replace it with the fragment's ID.

    Example in Kotlin:

    fun aTestFuction() {
       val existingFragment = MyExistingFragment() //Get it from somewhere, this is a dirty example
       val newFragment = MyNewFragment()
       replaceFragment(existingFragment, newFragment, "myTag")
    }
    
    fun replaceFragment(existing: Fragment, new: Fragment, tag: String? = null) {
        supportFragmentManager.beginTransaction().replace(existing.id, new, tag).commit()
    }
    

提交回复
热议问题