Trying to call a method in my activity from a fragment. I want the fragment to give the method data and to get the data when the method return. I want to achieve similar to call on a static method, but without the use of static because it create problems in the activity.
New to fragments so I need an easy and pedagogic explanation!
Thanks!
Best way of calling Activity from Fragment class is that make interface in Fragment and add onItemClick() method in that interface. Now implement it to your first activity and call second activity from there.
If you want to go back from Activity to Fragment. This is very simple just override onBackPressed() in your activity and call onBackPressed where you want.
From fragment to activty:
((YourActivityClassName)getActivity()).yourPublicMethod();
From activity to fragment:
FragmentManager fm = getSupportFragmentManager(); //if you added fragment via layout xml YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id); fragment.yourPublicMethod();
If you added fragment via code and used a tag
string when you added your fragment, use findFragmentByTag
instead:
YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentByTag("yourTag");
You should probably try to decouple the fragment from the activity in case you want to use it somewhere else. You can do this by creating a interface that your activity implements.
So you would define an interface like the following:
Suppose for example you wanted to give the activity a String and have it return a Integer:
public interface MyStringListener{ public Integer computeSomething(String myString); }
This can be defined in the fragment or a separate file.
Then you would have your activity implement the interface.
public class MyActivity extends FragmentActivity implements MyStringListener{ @Override public Integer computeSomething(String myString){ /** Do something with the string and return your Integer instead of 0 **/ return 0; } }
Then in your fragment you would have a MyStringListener variable and you would set the listener in fragment onAttach(Activity activity) method.
public class MyFragment { private MyStringListener listener; @Override public void onAttach(Context context) { super.onAttach(context); try { listener = (MyStringListener) context; } catch (ClassCastException castException) { /** The activity does not implement the listener. */ } } }
edit(17.12.2015):onAttach(Activity activity) is deprecated, use onAttach(Context context) instead, it works as intended
The first answer definitely works but it couples your current fragment with the host activity. Its good practice to keep the fragment decoupled from the host activity in case you want to use it in another acitivity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With