With the following code I can click a button to send a string from one fragment (Fragment A) into a MainActivity. How would I retrieve the string from the MainActivity and display it on a fragment B all in one go? I would like the fragments to act synchronized; to have Fragment B update itself as soon as I click the button in Fragment A. I can't seem to find anything in SO on this.
Interface:
public interface OnDataListener {
public void onDataReceived(String data);
}
Fragment A data listener:
OnDataListener mOnDataListener;
@Override
public void onAttach(Context context) {
try{
mOnDataListener = (OnDataListener) context;
Log.d(TAG, "onAttach was called" + context);
}catch (ClassCastException e){
Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage() );
}
super.onAttach(context);
}
Button logic in Fragment A's onCreateView:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String newTextString = editTextView.getText().toString();
mOnDataListener.onDataReceived(newTextString);
}
});
MainActivity data receiver
public class MainActivity extends AppCompatActivity implements OnDataListener {
@Override
public void onDataReceived(String data) {
Log.e(TAG, "MainActivity received this string " + data );
}
}