0

I have an activity, let's call it A, and it launches a fragment like so:

remoteFragment = new RemoteFragment();
getSupportFragmentManager()
        .beginTransaction()
        .replace(R.id.frameLayout_remote_activity, remoteFragment)
        .commit();

my remoteFragment looks something like this:

public Button okBtn;

public RemoteFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_remote, container, false);
    okBtn= view.findViewById(R.id.okBtn);

    return view;
}

public RemoteLayoutView getOkBtn() {
    return okBtn;
}

and in my activity I am trying to get it like so:

Button okBtnMessageNotWorking = remoteFragment.getOkBtn();

but okBtnMessageNotWorking is always null.

my question is how can I get the view objects from the fragment inside my activity?

Pawel
  • 15,548
  • 3
  • 36
  • 36
Finer
  • 19
  • 1
  • 8
  • Yes you definitely can, while you do not have to necessarily. If no other view in the current view hierarchy contains any other view with the same Id, you can call ``activity.findViewById()`` inside your activity to obtain any view. You just need to make sure your view if already inflated and shown before you expect to retrieve it by any means of using **findViewById()**. Fragment lifecycle doen not necessarily in full synch with its activity. – alperozge Jun 16 '20 at 13:20
  • @alperozge how can I make sure the view is inflated? – Finer Jun 16 '20 at 13:47
  • you could directly use the findViewByID in the activity itself right – Nitin Tej Jun 16 '20 at 14:30
  • you can implement a custom callback interface. Call the callback function from **onStart()** or **onResume()** of your fragment. For an implementation example of that pattern: https://stackoverflow.com/questions/14439941/passing-data-between-fragments-to-activity – alperozge Jun 16 '20 at 21:27
  • By the way, I should correct a mistake of myself: "You just need to make sure your view if already inflated and **_attached to full view hierarchy_** before you expect to retrieve it by any means of using findViewById()." – alperozge Jun 16 '20 at 21:47
  • When do you call `getOkBtn()` ? You are probably calling it to early. – David Wasser Jun 17 '20 at 14:10

0 Answers0