如何从另一个类调用MainActivity中的方法? [英] How to call a method in MainActivity from another class?

查看:849
本文介绍了如何从另一个类调用MainActivity中的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在主要活动中声明方法时,如何在另一个类中调用方法startChronometer?

How do I call the method startChronometer in another class when the method is declared inside the main activity?

内部MainActivity:

public void startChronometer() {
    mChronometer.start();
    showElapsedTime();
}

在另一堂课中,我试图做到这一点:

Inside another class, I tried to do this:

MainActivity mActivity;
mActivity.startChronometer();

但是发生了一个错误,提示:

But an error occurred which said:

java.lang.NullPointerException. 

我是否还需要在代码中添加什么?

May I know what more I need to add to the code?

推荐答案

您可以通过以下类型的强制转换轻松地从Activity内的任何Fragment调用方法:

You can easily call a method from any Fragment inside your Activity by doing a cast like this:

Java

((MainActivity)getActivity()).startChronometer();

科特林

(activity as MainActivity).startChronometer()

在执行此操作之前,请记住要确保该Fragment的活动实际上是MainActivity.

Just remember to make sure this Fragment's activity is in fact MainActivity before you do it.

希望这会有所帮助!

这篇关于如何从另一个类调用MainActivity中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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