在Kotlin中将值从Activity传递给Fragment [英] Passing a value from Activity to Fragment in Kotlin

查看:1304
本文介绍了在Kotlin中将值从Activity传递给Fragment的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中创建了一个底部导航活动,其中包含一个活动和两个片段.在主要活动中,我将值存储在变量中,但是如果将值传递给片段,则会收到NullPointer异常错误.我在项目中使用kotlin,对您的帮助表示感谢. 期望

I created a bottom navigation activity in my project, which contains one activity and two fragments. In Main Activity I have value stored in a variable but if I pass the value to the fragments then I am getting NullPointer Exception error. I am using kotlin in my project and any help is appreciated. Expectation

Get Value into Fragment from MainActivity. MainActivity--->TestOneFragment

使用的语言

Kotlin

主要活动

class Test : AppCompatActivity(), BottomNavigationView.OnNavigationItemSelectedListener
{
    private val KEY_POSITION = "keyPosition"
    private var navPosition: BottomNavigationPosition = BottomNavigationPosition.ONE
    private lateinit var toolbar: Toolbar
    private lateinit var bottomNavigation: BottomNavigationView

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        restoreSaveInstanceState(savedInstanceState)
        setContentView(R.layout.activity_test)
        toolbar = findViewById(R.id.toolbar)
        bottomNavigation = findViewById(R.id.bottom_navigation)
        setSupportActionBar(toolbar)
        initBottomNavigation()
        initFragment(savedInstanceState)
        var Name:String=intent.getStringExtra("name")
        println("Test CLLicked: $Name")


        //This code is to pass the value to Fragment
        var bundle=Bundle()
        bundle.putString("name",Name)
        var frag=TestFragment()
        frag.arguments=bundle
    }

    override fun onSaveInstanceState(outState: Bundle?)
    {
        outState?.putInt(KEY_POSITION, navPosition.id)
        super.onSaveInstanceState(outState)
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean
    {
        navPosition = findNavigationPositionById(item.itemId)
        return switchFragment(navPosition)
    }

    private fun restoreSaveInstanceState(savedInstanceState: Bundle?)
    {
        savedInstanceState?.also {
            val id = it.getInt(KEY_POSITION, BottomNavigationPosition.ONE.id)
            navPosition = findNavigationPositionById(id)
        }
    }

    private fun initBottomNavigation()
    {
        bottomNavigation.active(navPosition.position)
        bottomNavigation.setOnNavigationItemSelectedListener(this)
    }

    private fun initFragment(savedInstanceState: Bundle?)
    {
        savedInstanceState ?: switchFragment(BottomNavigationPosition.ONE)
    private fun switchFragment(navPosition: BottomNavigationPosition): Boolean {
        return supportFragmentManager.findFragment(navPosition).let {
            if (it.isAdded) return false
            supportFragmentManager.detach() // Extension function
            supportFragmentManager.attach(it, navPosition.getTag()) // Extension function
            supportFragmentManager.executePendingTransactions()
        }
    }
    private fun FragmentManager.findFragment(position: BottomNavigationPosition): Fragment
    {
        return findFragmentByTag(position.getTag()) ?: position.createFragment()
    }
}

TestOneFragment

 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View? {
    val testName= arguments!!.getString("name")
....
}

错误

kotlin.KotlinNullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)

推荐答案

以下是用于创建FragmentsnewInstance模式的示例.

Here is an example of the newInstance pattern for creating Fragments.

这是在companion object中,这几乎只是说这些东西是静态的"的一种方式.

This is within a companion object, which is pretty much just a way to say "these things are Static."

首先,您应该为Bundle名称定义常量,这将有助于使所有内容保持一致.接下来,定义一个使用您的参数的newInstance方法,例如name.

First, you should define constants for your Bundle names, this will help keep everything aligned. Next, define a newInstance method that takes your parameters, such as the name.

然后在其中创建Fragment并将其返回.这样,您的Activity不必担心Bundle或其他任何问题.您所有的逻辑都在一个位置内(用于存储/检索),所有位置都在您的Fragment内.

And within there, you will create your Fragment and return it. This way, your Activity doesn't have to worry about the Bundle or anything. All your logic is within one place, for storing/retrieving, all within your Fragment.

class TestOneFragment {

    companion object {
        const val ARG_NAME = "name"


        fun newInstance(name: String): TestOneFragment {
            val fragment = TestOneFragment()

            val bundle = Bundle().apply {
                putString(ARG_NAME, name)
            }

            fragment.arguments = bundle

            return fragment
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val name = arguments?.getString(ARG_NAME)
        // ...
    }
}

现在,您可以通过执行以下操作轻松获得Fragment.

And now, you can easily get your Fragment by doing the following.

class Test : AppCompatActivity(), BottomNavigationView.OnNavigationItemSelectedListener {

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        // ...

        val name = intent.getStringExtra("name")

        // Creating the new Fragment with the name passed in.
        val fragment = TestFragment.newInstance(name)
    }

}

希望有帮助!

这篇关于在Kotlin中将值从Activity传递给Fragment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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