简体   繁体   English

从对象开始活动

[英]Start Activity from Object

The usual way to start an activity is 开始活动的通常方法是

Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);

Is there a way to start an Activity from an Object?.. like 有没有办法从一个对象开始一个活动?

SecondActivity var = new SecondActivity();
var.start();

Something like that..?! 那样的东西..?!

Simply pass the Context to your CustomObject and start the Activity using it: 只需将Context传递给CustomObject并使用它启动Activity:

public class CustomObject {

    Context c;
    // and some other fields here...

    public CustomObject(Context c) {
        this.c = c;
    }

    public void startActivity() {

        Intent intent = new Intent(c, SecondActivity.class);
        c.startActivity(intent);
    }

    // and some other methods here...
}

And inside your Activity that creates the Object: 在创建对象的活动内部:

CustomObject obj = new CustomObject(this);
obj.startActivity();

I think you might have this backwards. 我认为您可能对此倒退。 It sounds like you should send a reference to an object containing your preference data from one from one Activity to another. 听起来您应该从一个活动向另一个活动发送对包含您的首选项数据的对象的引用。 You can do this using the setXxxExtra() methods in the Intent class. 您可以使用Intent类中的setXxxExtra()方法来执行此操作。

To send data back from the second Activity to the first Activity, you should first start the second Activity using startActivityForResult() and then override onActivityResult() in your main Activity. 要将数据从第二个Activity发送回第一个Activity,您应该首先使用startActivityForResult()启动第二个Activity,然后在主Activity中覆盖onActivityResult() The Android developer pages have a very good example about how to do this . Android开发人员页面上一个很好的示例,说明了如何执行此操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM