Home » Java » java – How to Call Method in Fragment From Parent Activity?-Exceptionshub

java – How to Call Method in Fragment From Parent Activity?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

**Here is the Fragment I want call getAvailableWebsites(); from parent Activity **

public class Earn extends Fragment {


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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_earn, container, false);
}
public void getAvailableWebsites(){
    Toast.makeText(getActivity(),"Called From Activity",Toast.LENGTH_LONG).show();
}

}

How to&Answers:

you can try below option in your Activity:

Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.container);
if (fragment != null && fragment instanceof YourFragment) {
    ((YourFragment) fragment).yourFragmentMethod();
}

Hope this helps you..

Answer: