Q:

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!

A:

From fragment to activty:

((YourActivityClassName)getActivity()).yourPublicMethod();

From activity to fragment:

FragmentManager fm = getSupportFragmentManager();//if you added fragment via layout xmlYourFragmentClass 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");

 

原文取自 http://stackoverflow.com/questions/12659747/call-an-activity-method-from-a-fragment

 


arrow
arrow

    Frank 發表在 痞客邦 留言(0) 人氣()