从片段调用活动的方法片段、方法

2023-09-11 12:50:56 作者:与诸葛亮放纵

试图从一个片段调用一个方法,在我的活动。我想片段给该方法的数据和获取数据的方法返回的时候。欲实现类似于上一个静态方法调用,但不使用静态的,因为它建立在活动的问题。

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!

谢谢!

推荐答案

从片段activty:

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

从活动片段:

FragmentManager fm = getSupportFragmentManager();

//if you added fragment via layout xml
YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id);
fragment.yourPublicMethod();

如果您添加通过code片段,并使用了标记字符串时,您添加的片段,使用 findFragmentByTag 来代替:

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");