Crispen Smith Crispen Smith - 4 months ago 15x
Android Question

Android set the text of TextView inside a Fragment - where the Fragment may have already mounted

Within my Android app I'm looking to hotswap the text in a Fragment based on a button press in another fragment.

The Buttons fragment has 6 buttons, each of which need to invoke a configured view of output fragment, so that when "BUtton 1" is pressed in Buttons, a TextView myText is configured to say "Button 1 was pressed" and so on, for 2 - 6.

I've tried instantiating a member version of the TextView inside onViewCreated, and several other strategies but I can't seem to get this not to crash.

Is there an established pattern for this?

//MainActivity Java
public class MainActivity extends AppCompatActivity
implements StringsFragment.OnStringsInteractionListener,
ProgressFragment.OnProgressInteractionListener {

public void onStringButtonClick(Integer string) {
fm = getSupportFragmentManager();

if(liveStringFlag != true) {
liveStringFlag = true;
fm.beginTransaction().add(, stringFragment).commit();


What does stringFragment.updateString need to look like, and what else needs to happen to make it work?


What isn't immediately clear about this scenario is that it's sometimes tricky to know when onViewCreated has been called. In effect this is a race condition and the update method or the onViewCreated may be called first. For this reason it's important to carefully manage state.

Public Class stringFragment extends Fragment {
  private TextView textString;
  private Boolean viewable = false;
  private String string = ""; 

  public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
        textString = (TextView) view.findViewById(;
    if(string != null) {

    viewable = true;


  public void updateStringData(String s ) {
    string = s;

    if(viewable == true) {