如何调用一个函数从主要活动活动 [英] how to call a function in an activity from main activity

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

问题描述

公共类活性1扩展活动{

public class Activity1 extends Activity {

billreminder br;//billreminder is a function in activity2

public void onCreate(Bundle savedInstanceState);



setContentView(R.layout.main);

br.read(c);//c is a string

}

我们如何调用读取功能。

how do we call read function.

推荐答案

有几个方法可以做到这一点。您可以使功能活性2静态函数。然后,您可以调用它像这样: Activity2.read(C)

There are a couple of ways you can do this. You can make the function in activity2 a static function. You can then call it like so: Activity2.read(c)

另一种方式,是从活动1传递的意图,活性2如下:

Another way, is to pass an intent from Activity1 to Activity2 as follows:

在活动1:

Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra("c", c);
//this will put a callback in the onActivityResult method for the Activity1 class
startActivityForResult(intent, requestCode);//requestCode is an int

在其onCreate方法内活性2:

in activity2 inside its onCreate method:

Bundle extras = getIntent().getExtras();

if(extras != null) {
    c = extras.getString("c");
    if(c != null && !"".equals(c)) {
        read(c);
    }
    setResult(resultCode);//resultCode is an int
}

在活动1 again1:

in activity1 again1:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   //detect resultCode or requestCode, and do whatever you want
   ....
}

避免继承应用程序类。从的android文档

通常没有必要的子类的应用。在大多数情况下,
  静态单身能够以更模块化提供相同的功能
  办法。如果你单身需要一个全球范围内(例如注册
  广播接收器),所述函数来检索它可以给出一个
  上下文内部使用Context.getApplicationContext()的时候
  首先构建单。

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

另外,我觉得你是困惑。您需要调用对象的方法。

Also, I think you are confused. You need to call a method on an object.

BR billreminder; // billreminder是活性2函数

billreminder br;//billreminder is a function in activity2

是错误的。我想你说的意思是BR对象。

is wrong. I think you meant that br is an object.

这篇关于如何调用一个函数从主要活动活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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