如何从片段(kotlin)中打开片段 [英] How do i open fragment from fragment (kotlin)

查看:136
本文介绍了如何从片段(kotlin)中打开片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用ClickListener将片段移动到片段的方法;但我不知道如何将碎片逐个碎片化.

I'm finding a way to move fragment to fragment by using ClickListener; but I have no idea how to move fragment to fragment.

我想这样移动:

一个片段有4张Cardview

A fragment have 4 cardview

点击1张卡片视图:移至片段B
点击2卡视图:移至片段C
点击3张卡片:将其移至片段D
点击4张卡片:将其移至片段F

click 1 cardview : move to fragment B
click 2 cardview : move to fragment C
click 3 cardview : move to fragment D
click 4 cardview : move to fragment F

我已经使用下面的代码将片段移动到活动中

I have done fragment move to activity by using code below

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        power655Card.setOnClickListener {
            val intent = Intent (getActivity(), Power655Activity::class.java)
            getActivity()?.startActivity(intent)
        }

推荐答案

科特林(Kotlin)中,如果您想在活动中加载各种片段,则可以创建一个函数,在需要加载该函数的任何地方调用片段.

In Kotlin, if you want to load various fragment inside activity, you can make one function which you call wherever required to load the fragment.

private fun loadFragment(fragment: Fragment){
    val transaction = supportFragmentManager.beginTransaction()
    transaction.replace(R.id.fl_main, fragment)
    transaction.disallowAddToBackStack()
    transaction.commit()
}

如果要从片段中加载片段,

And if you want to load fragment from a fragment,

    val transaction = activity.supportFragmentManager.beginTransaction()
    transaction.replace(R.id.fl_main, SecondFragment())
    transaction.disallowAddToBackStack()
    transaction.commit()

在上面的代码Spinnet中,SecondFragment()是您要加载的片段的实例.因此我们也可以传递片段的实例,如上所示.

In the above code spinnet, SecondFragment() is the instance of the fragment which you wish to load. So we can also pass the instance of the fragment as shown above.

这篇关于如何从片段(kotlin)中打开片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆