从片段内部调用Activity方法 [英] Calling Activity Method From Inside A Fragment

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

问题描述

我正在尝试从片段"屏幕中激活一个方法.

I am trying to call a method in an activty from a Fragment screen.

我有一个名为myMethod()的方法,该方法位于名为MyActivity的活动中; 我有一个名为Screen1Fragment的片段.

I have a method called myMethod() which is in an activity called MyActivity; I have a fragment called Screen1Fragment.

我想从Screen1Fragment内部调用MyActivity.myMethod(),但是我不确定该怎么做.

I would like to call MyActivity.myMethod() from inside the Screen1Fragment but I am not sure how to do this.

以前,Screen1Fragment是一项活动,因此我扩展了MyActivity,以便可以直接调用 myMethod(). 但是我不得不将活动更改为片段以使用滑动标签.

Previously the Screen1Fragment was an activity and so I was extending MyActivity so that I could directly call myMethod(). But I have had to change the activity to a fragment for sliding tabs usage.

谢谢.

推荐答案

在片段中使用getActivity().

MyActivity activity = (MyActivity) getActivity();
activity.myMethod();

如果不确定您的片段是否已附加到MyActivity,则

if you are not sure if your fragment is attached to MyActivity then

 Activity activity = getActivity();
 if(activity instanceof MyActivity){
      MyActivity myactivity = (MyActivity) activity;
      myactivity.myMethod();
 }

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

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