Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Studio change TextView fragment from activity

I have created an activity in activities folder and one fragment in fragments folder. Look how my fragment builds: https://i.sstatic.net/jIt9W.png

Some else tried like me by doing this Android : Update Tab Layout(fragments) textviews from an activity, but I don't understand what was the solution.

How can I send data like string from activity to this fragment and I want it in tab2 (like in picture)?

I try many ways and I didn't find solution

From my activity

Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

And from Fragment

String strtext = getArguments().getString("edttext");    

does not work :(

like image 325
sharon2469 Avatar asked Feb 02 '26 11:02

sharon2469


1 Answers

I can recommend an alternative solution - using a 3rd party library called EventBus. It's quite easy to use and it's very useful for different scenarios. Create a custom event, something like this:

public class MyEvent {
private String text;

public MyEvent(String text) {
    this.text = text;
}

public String getText() {
    return text;
}

public void setText(String text) {
    this.text= text;
}

And simply in your Activity, post this event with the text you wish to send to the fragment:

EventBus.getDefault().post(new MyEvent(yourTextString);

Now simply register the eventBus in onCreate of your Fragment:

EventBus.getDefault().register(this);

And create a method that listens for the event like this:

@Subscribe
public void onMyEvent(MyEvent myEvent){
    String text = myEvent.getText();
    //Now you can do whatever you wish with this text
}
like image 191
Vucko Avatar answered Feb 04 '26 01:02

Vucko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!