从片段调用活动方法 [英] Call an activity method from a fragment

查看:32
本文介绍了从片段调用活动方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试从片段中调用我的活动中的方法.我希望片段提供方法数据并在方法返回时获取数据.我想实现类似于对静态方法的调用,但不使用静态方法,因为它会在活动中产生问题.

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!

谢谢!

推荐答案

从片段到活动:

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

如果您通过代码添加片段并在添加片段时使用了 tag 字符串,请改用 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");

这篇关于从片段调用活动方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆