简体   繁体   中英

how to call a ui component of a fragment from another fragment Android

how can I call a ui component defined in a fragment A from a fragment B. I have declared a texview in fragment A and I want to set a calculated value in fragment B in said textview.I use java to develop the app. Greetings

You don't, directly. There's a couple of ways you can do this, but Fragment A and Fragment B shouldn't know about each other. They're independent. Instead, Fragment A should define an interface it calls when an event (such as changing the value of its textview) occurs. This can be a callback function in an interface, a message bus, an Observable, a view model, or a variety of other mechanisms. In Fragment B, you have an API that sets the value. This can be a function call, passing in an observable you subscribe to which sets the value, passing in a message bus that will tell it when the value changes, using a ViewModel and subscribing to updates to that, etc.

Then the Activity is in charge of wiring up the interface on A to effect the interface on B. Which way you choose depends on what technologies the rest of your app uses.

Why you have to call ui component you can pass your calculated value in fragment B or you can use eventbus library for that. implementation("org.greenrobot:eventbus:3.3.1")

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