简体   繁体   中英

Android Studio: How do I get a button in main activity to do something in a fragment when they aren't directly connected?

So I guess they could be directly connected, but I'm unsure how I'd access the fragments method's from the main activity in this situation.

I'm using a navigation bar on the main activity and I'd like a button in the nav bar to do an action inside of one of the fragments connected to the navigation bar. Is there anyway I could do this?

In your Fragment, create a interface and setter.

    private lateinit var listener: YourFragmentListener

    interface YourFragmentListener {

        fun doSomething()
    }

    fun setListener(listener: YourFragmentListener){

        this.listener = listener
    }

Make your Activity implements the listener

    class YourActivity : AppCompatActivity(), YourFragmentListener {

       override fun doSomething(){

         //do what you want
       }
    }

when you create the fragment, also set the listener.

   val fragment = YourFragment()
   fragment.setListener(this)

finally, in your fragment, you can use listener everywhere to callback to activity

  listener.doSomething()

Hope this helps.

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