如何在另一个类中使用onActivityResult

问题描述 投票:3回答:3

我想在不扩展活动的类中使用onActivityResult,但是这个类有一个全局变量作为活动的实例。这个类与此类似:

public class myClass(){
    public Activity myActivity;
    .
    .
    .
    // I want to add onMyActivityResult here
}

我正在寻找这样的东西:

myActivity.setOnActivityResult...

谢谢!

android onactivityresult
3个回答
3
投票

你可以做到以下几点

public class myClass(){

    public static void activityResult(int requestCode, int resultCode, Intent data){

          //right your code here .
   }
}

并在您的CLASS EXTENDS ACTIVITY中写入onActivityResult方法:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       myClass.activityResult(requestCode,resultCode,data);
    }

感谢这个答案:qazxsw poi


1
投票

这不可能覆盖实例onActivityResult(),但可以按照以下方式执行。主要的想法是创建一个在代码中调用自定义函数的类;在这种情况下

也就是说,您的活动类必须通过ABase而不是Activity来扩展:

https://stackoverflow.com/a/21780532/3818437

然后,public class yourClass extends ABase{ //your usual code is here. } 看起来像这样:

ABase

在你的公共myClass中使用public class ABase extends Activity { private Callable<Void> clb;//this function will be called protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (clb != null) { try { clb.call(); } catch (Exception e) { e.printStackTrace(); } } } public void setMyCallable(Callable<Void> callable){ this.clb = callable; } } act而不是public ABase;有一个public Activity act例如使用:

setSomeFunction()

0
投票
public class myClass {
public ABase act;
public static setSomeFunction() {
    if (act != null) {
        Callable<Void> clb = new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    Log.d(TAG, "is Called!");
                    return null;
                }
            }
        act.setMyCallable(clb);

        }
    }
}

public class MyActivity extends Activity {

    public interface IResult {
        void call(Intent data);
    }

    public IResult r;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) return;
        if (r == null) return;

        r.call(data);
    }

    void startZ() { Z.startZ(this); }
    void startY() { Y.startY(this); }
}

class Z {
    public static void startZ(MyActivity a) {
        a.r = data -> {
            //...YOUR CODE HERE...
        };

        a.startActivityForResult(
                new Intent(a, ZActivity.class),
                request_code___not_needed_because_only_one_activity_lives);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.