简体   繁体   中英

Editext Value Getting Null when I call from Activity to Fragment

Activity -> Fragment

I have a one button on my Activity. i want to get Value from Editext which is present in Fragment. when i call from Activity i get Null Value of Editext.

MainActivity.kt Code

buttonOne?.setOnClickListener {
        val frgment = MyFragment().getInstance()
        frgment?.buttonClick()
    }

MyFragment.kt Code

fun getInstance(): MyFragment? {
        return MyFragment()
    }

    fun buttonClick(){
        val value = et_fragment_first_name?.text.toString().trim()
        Log.e("Fragment", "FirstName $value")
}

Can anybody help me about it? I don't want to use Listner

What you just did is that you created a new instance of the fragment instead of getting the instance of the current active fragment, that is why you are getting a null. You can use FragmentManager to get a fragment by tag or Id

MyFragment myFragment = (MyFragment)getSupportFragmentManager().findFragmentByTag("MY_FRAGMENT");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM