Reputation: 6666
I have a fragment where I wish to call a method from the FragmentActivity that contains this fragment. I defined a method in FragmentTabs(extends FragmentActivity) that sets the lastTab fragment on a specific event in the fragment. For some reason getActivity().SomeUserDefinedActivity() cannot be resolved.
Here is the code explaining my problem :
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
testButton = (Button)getView().findViewById(R.id.button1);
testButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
Log.i("FragmentTest", "Button1 Clicked");
TestFragment2 f2 = new TestFragment2();
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.realtabcontent, f2);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
// This is where I want to call FragmentTabs method SetLastFragment, but I cannot access it.
getActivity().SetLastFragment(f2);
}
});
}
This is the method I wish to call in FragmentTabs:
public void SetLastFragment(Fragment f)
{
mTabManager.SetLastTabFragment(f);
}
Upvotes: 2
Views: 8430
Reputation:
getActivity()
returns just an Activity instance. This can be any activity that embeds your fragment. SetLastFragment()
is a method of one specific activity of yours, named FragmentTabs
. Not all activities have this method.
Which means you have to cast it to your specific activity class. If you use your fragment in multiple activties, you should also check if the correct activity is used, e.g. via the instanceof
operator:
Activity a = getActivity();
if(a instanceof FragmentTabs) {
((FragmentTabs) a).SetLastFragment(f2);
}
Upvotes: 16