【问题标题】:Forward one Fragment to another Fragment in Kotlin在 Kotlin 中将一个 Fragment 转发到另一个 Fragment
【发布时间】:2018-12-29 21:43:10
【问题描述】:

我的主要活动中有两个片段。如果我单击一个片段项目,则它需要移动到另一个下一个片段。如果它的活动到活动,那么我可以使用意图,如果它与片段有关,那么我不确定。任何帮助表示赞赏。

使用的语言

Kotlin

片段

OneFragement----->SecondFragment

代码

适配器类

itemView.setOnClickListener {

            Log.d("Test Clicked","Test Clicked")
        }

FragmentOne

val ft = fragmentManager!!.beginTransaction()
    ft.replace(R.id.Two, SecondFragment(), "NewFragmentTag")
    ft.commit()

【问题讨论】:

  • 片段事务对你不起作用是什么问题解释一下?
  • 它不工作并出现空指针异常。
  • 空指针在哪一行共享错误日志
  • 如果您查看我的问题,我询问了人们的建议。我提到我不确定将一个片段转发到另一个片段。
  • it need to move to another next fragment 这意味着你需要片段交易

标签: android android-fragments android-intent kotlin onclicklistener


【解决方案1】:

MainActivity

fun replaceFragment(fragment: Fragment, tag: String) {
    supportFragmentManager.beginTransaction()
        .replace(R.id.container, fragment, tag).addToBackStack("").commit()
}

FragmentTwo

class FragmentTwo:Fragment(){

 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
   //your  code
}
 companion object {
    val TAG = FragmentTwo::class.java.simpleName
    @JvmStatic
    fun newInstance() = FragmentTwo()
  }
}

FragmentOne

class FragmentOne:Fragment(){

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

fun onItemSelected(){
    val frag=FragmentTwo.newInstance()
    (activity as MainActivity).replaceFragment(frag,FragmentTwo.TAG)
}
 companion object {
    val TAG = FragmentOne::class.java.simpleName
    @JvmStatic
    fun newInstance() = FragmentOne()
  }
}

在适配器类中

itemView.setOnClickListener{
    frag.onItemSelected()
}

【讨论】:

  • 欲了解更多信息,您可以参考我在您的另一篇帖子中的回答HERE
猜你喜欢
  • 1970-01-01
  • 2014-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-06
  • 1970-01-01
  • 1970-01-01
  • 2021-02-19
相关资源
最近更新 更多