0

I want to create fragment with Arguments,

and refer to this post [ Do fragments really need an empty constructor? ].

But not work, I don't know how to fix it.

Code:

Fragment

public class TestFragment extends Fragment {
  private final static String BUNDLE_TITLE = "title";
  private RelativeLayout rootView;
  private String title = "";

  public static TestFragment newInstance(String titleName){
    Bundle bundle = new Bundle();
    bundle.putString(BUNDLE_TITLE,titleName);
    TestFragment testFragment = new TestFragment();
    testFragment.setArguments(bundle);
    return testFragment;
  }

  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    if (rootView == null) {
        rootView = (RelativeLayout) inflater.inflate(R.layout.find_mac, container, false);
    }
    return rootView;
  }

  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle data = getArguments();
    if(data != null){
        this.title = getArguments().getString(BUNDLE_TITLE,"");
    }
  }

  String getTitle() {
    return title;
  }
}

And in Activity,

@Override
protected void onStart() {
  super.onStart();
  TestFragment testFragment = TestFragment.newInstance("hello");
  Log.d("debug","get title:"+testFragment.getTitle());
}

The Log show only "get title:",

I can't get the title "hello" word.

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
KBKai
  • 353
  • 1
  • 4
  • 18

1 Answers1

3

This is because when you calling:

TestFragment testFragment = TestFragment.newInstance("hello");
Log.d("debug","get title:"+testFragment.getTitle());

the testFragment fragment is not yet finished created. Because it is an asynchronous process.

So, you need to create a listener in activity to tell that the fragment is created, then in it, you can get the title.

You can read Communicating with Other Fragments for implementing the listener.

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96