【发布时间】:2014-01-10 00:24:33
【问题描述】:
我是安卓开发新手 我现在调用一个意图我如何从调用的活动中获得结果 谁能告诉我如何执行这项任务? 我称之为意图。
Intent I = new Intent (this ,abc.class);
startActivity(i);
谢谢
【问题讨论】:
-
“我如何从被调用的活动中获得结果”是什么意思?
我是安卓开发新手 我现在调用一个意图我如何从调用的活动中获得结果 谁能告诉我如何执行这项任务? 我称之为意图。
Intent I = new Intent (this ,abc.class);
startActivity(i);
谢谢
【问题讨论】:
使用startActivityForResult,然后在您的FirstActivity 中覆盖onActivityResult。
在FirstActivity
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
startActivityForResult(intent, 2);// Activity is started with requestCode 2
覆盖onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String message=data.getStringExtra("MESSAGE");
Log.i("Message is",message);
// logs Testing
}
}
在SecondAcivity
Intent intent=new Intent();
intent.putExtra("MESSAGE","Testing");
setResult(2,intent);
finish();//finishing activity
参考文档:
例子:
http://www.javatpoint.com/android-startactivityforresult-example
【讨论】:
要参加第二个活动,请在您的第一堂课中使用 startActivityForResult
Intent callIntent = new Intent(FirstClass.this, SecondClass.class);
startActivityForResult(callIntent, 1);
然后像这样覆盖你的第一个类中的 onActivityResult 方法
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == 1) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// get values from data
}
} }
如果您想发送,请在您的第二堂课中执行此操作以返回 一流的东西。将此存储在您的意图中。
Intent result = new Intent(); setResult(Activity.RESULT_OK, result);
finish();
【讨论】:
你可以得到结果调用活动
以startActivityForResult(intent, 0); 开始活动
在调用活动中添加以下方法
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
// do your task
} else if (resultCode == RESULT_CANCELED) {
// do your task
}
}
}
【讨论】:
在你的主类中......
static final int CODE_REQUEST = 1; // The request code
....
Intent pickContactIntent = new Intent(MainClass.this, CallingClassName.class);
startActivityForResult(pickContactIntent, CODE_REQUEST);
.......
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
}
在你的调用类中
Intent result = new Intent();
setResult(Activity.RESULT_OK, result);
finish()
【讨论】: