在我的Android应用程序中,我有一个主要活动,通过意图创建另外两个子活动。现在,子活动都将结果返回到主活动。在我的主要活动中, 我如何处理两个“onActivityResult(int requestCode,int resultCode,Intent data)”,因为它在给定的类中不能有两个具有相同名称的方法。希望我的问题很清楚..
由于
答案 0 :(得分:10)
您更改了致电requestCode
时使用的startActivityForResult
。
编辑:例如,我使用它:
startActivityForResult(i, App.REQUEST_ENABLE_BT);
和此:
startActivityForResult(i, App.MANUAL_INPUT);
然后你按照这样过滤结果:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
switch(requestCode){
case App.REQUEST_ENABLE_BT:
if(resultCode != RESULT_OK){
Toast.makeText(this, getString(R.string.label_bluetooth_disabled), Toast.LENGTH_LONG).show();
}
break;
case App.MANUAL_INPUT:
break;
}
}
答案 1 :(得分:10)
这就是requestCode
的用途。所以你有这样的设置
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
case ACTIVITY1:
if(resultCode == RESULT_OK)
Toast.makeText(getApplicationContext(), "Activity 1 returned OK", Toast.LENGTH_LONG).show();
break;
case ACTIVITY2:
if(resultCode == RESULT_OK)
Toast.makeText(getApplicationContext(), "Activity 2 returned OK", Toast.LENGTH_LONG).show();
break;
}
ACTIVITY1和ACTIVITY2在Activity
中是常量。你会这样称呼他们:
startActivityForResult(activity1Intent, ACTIVITY1);
和
startActivityForResult(activity2Intent, ACTIVITY2);
答案 2 :(得分:3)
可以从结果意图参数中的子活动中返回任何类型的数据:
子活动:
Intent intent = new Intent ();
intent.putExtra ("string_1", "hello");
intent.putExtra ("string_2", "world");
intent.putExtra ("int_1", 1000);
intent.putExtra ("long_1", 2000l);
activity.setResult (Activity.RESULT_OK, intent);
_
家长活动:
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent intent)
{
if (resultCode == Activity.RESULT_OK)
{
String string_1 = intent.getStringExtra ("string_1", "");
String string_2 = intent.getStringExtra ("string_2", "");
int int_1 = intent.getIntExtra ("int_1", 0);
long long_1 = intent.getLongExtra ("long_1", 0);
}
}
答案 3 :(得分:1)
您可以使用swicth请求代码来获取不同的结果
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (1):
{
// do this if request code is 1.
}
break;
case (2):
{
// do this if request code is 2.
}
break;
}