To interact with your BlankFragment object, I would use the following method recommended in Android Support Docs - I believe that this is what you are trying to achieve, and it will be suitable since your BlankFragment object BlankFragment hosted by MainActivity :
public class MainActivity extends FragmentActivity implements BlankFragment.OnFragmentInteractionListener { private BlankFragment fragment = null; private android.support.v4.app.FragmentManager manager = null; private android.support.v4.app.FragmentTransaction ft; public void onFragmentInteraction(Uri uri){ Log.i("Tag", "onFragmentInteraction called"); } protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (manager == null) manager = getSupportFragmentManager(); if(manager.findFragmentById(R.id.fragment_container) == null) {
To contact your snippet, you must do the following:
if(fragment == null) { fragment = (BlankFragment) manager.findFragmentById(R.id.fragment_container); }
Then you can call any methods related to fragment
If it's the other way around (linking from fragment to activity), you will need to do the following in BlankFragment to form a link with the parent Activity :
//Class variable... OnFragmentInteractionListener mCallback; @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallback = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } }
You may have forgotten about this last step, which may explain your mistake. Then you would use:
mCallback.onFragmentInteraction(uri);
To contact MainActivity
source share