Reputation: 1215
I created an interface so I can set text on a FragmentB when I press a TextView on FragmentA. Something is not working and I can't figure this out.
I've created an interface called Communicator:
public interface Communicator {
void respond(String data);
}
On FragmentA I've set a reference on the interface called Communcator and an OnClickListener on the TextView:
Communicator comm;
homeTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
comm.respond("Trying to set text on FragmentB from here");
}
});
FragmentB, set my method to change text:
public void setText(final String data) {
startTripTxt.setText(data);
}
Finally in MainActivity I've implemented the interface .. I think here is where I'm doing something wrong:
@Override
public void respond(String data) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container_main, new FragmentB(), "fragment2").addToBackStack(null).commit();
FragmentB fragmentB= (FragmentB) getSupportFragmentManager().findFragmentByTag("fragment2");
if (fragmentB != null) {
fragmentB.setText(data);
}
}
Fragment 2 loads, but the text is empty.
Upvotes: 0
Views: 159
Reputation: 2954
Fragment 2 loads, but the text is empty.
You implement Communicator
is ok but the way you call FragmentB
and passing data is not ok. That 's is the reason why you cannot get text from FragmentB
. the right way to send data to FragmentB
should be like this:
public static FragmentB createInstance(String data) {
FragmentB fragment = new FragmentB();
Bundle bundle = new Bundle();
bundle.putString("data", data);
fragment.setArguments(bundle);
return fragment;
}
And you can get data from FragmentB by:
Bundle bundle = getArguments();
if (bundle != null) {
String data = bundle.getString("data");
}
Upvotes: 2
Reputation: 843
It looks like after you declare fragmentB, you're meaning to set the text on that fragment. You are Instead calling trainFinderFragment.setText(). Is that your issue?
FragmentB fragmentB= (FragmentB) getSupportFragmentManager().findFragmentByTag("fragment2");
if (fragmentB != null) {
fragmentB.setText(data);
}
Upvotes: 1