如何从 TabHost 活动返回结果 (startActivityForResult)? [英] How to return a result (startActivityForResult) from a TabHost Activity?
问题描述
我的示例中有 3 个类:A类,主要活动.A 类调用一个 startActivityForResult:
I have 3 classes in my example: Class A, the main activity. Class A calls a startActivityForResult:
Intent intent = new Intent(this, ClassB.class);
startActivityForResult(intent, "STRING");
B 类,这个类是一个 TabActivity:
Class B, this class is a TabActivity:
Intent intent = new Intent(this, ClassC.class);
tabHost.addTab...
C班,这个班是一个常规的Activity:
Class C, this class is a regular Activity:
Intent intent = this.getIntent();
intent.putExtra("SOMETHING", "EXTRAS");
this.setResult(RESULT_OK, intent);
finish();
onActivityResult 在 Class A 中被调用,但是 resultCode 是 RESULT_CANCELED
而不是 RESULT_OK
并且返回的 Intent 为 null.如何从 TabHost 内的 Activity 返回某些内容?
onActivityResult is called in Class A, but the resultCode is RESULT_CANCELED
instead of RESULT_OK
and the returned intent is null. How do I return something from the Activity inside a TabHost?
我意识到问题是我的 C 类实际上在 B 类内部运行,而 B 类是将 RESULT_CANCELED
返回到 A 类的原因.我只是不知道有什么工作还在附近.
I realize that the problem is that my Class C is actually running inside of Class B, and Class B is what is returning the RESULT_CANCELED
back to Class A. I just don't know a work around yet.
推荐答案
天哪!花了几个小时下载了安卓源,终于找到了解决办法.
Oh, god! After spending several hours and downloading the Android sources, I have finally come to a solution.
如果您查看 Activity 类,您会看到 finish()
方法仅在 mParent
属性设置为 时才将结果发回空
.否则结果丢失.
If you look at the Activity class, you will see, that finish()
method only sends back the result if there is a mParent
property set to null
. Otherwise the result is lost.
public void finish() {
if (mParent == null) {
int resultCode;
Intent resultData;
synchronized (this) {
resultCode = mResultCode;
resultData = mResultData;
}
if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
try {
if (ActivityManagerNative.getDefault()
.finishActivity(mToken, resultCode, resultData)) {
mFinished = true;
}
} catch (RemoteException e) {
// Empty
}
} else {
mParent.finishFromChild(this);
}
}
所以我的解决方案是将结果设置为父活动(如果存在),如下所示:
So my solution is to set result to the parent activity if present, like that:
Intent data = new Intent();
[...]
if (getParent() == null) {
setResult(Activity.RESULT_OK, data);
} else {
getParent().setResult(Activity.RESULT_OK, data);
}
finish();
如果有人再次寻找此问题的解决方法,我希望这会有所帮助.
I hope that will be helpful if someone looks for this problem workaround again.
这篇关于如何从 TabHost 活动返回结果 (startActivityForResult)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!