在Android中startActivityForResult主要作用就是:
A-Activity需要在B-Activtiy中执行一些数据操作,而B-Activity又要将,执行操作数据的结果返回给A-Activtiy
//看效果
//看代码
- package sn.len.actres;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
- public class ActivityResultDemoActivity extends Activity
- {
- private Button button_start_task;
- private TextView TextView_result;
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- button_start_task=(Button) findViewById(R.id.button_start_task);
- TextView_result=(TextView) findViewById(R.id.TextView_result);
- button_start_task.setOnClickListener(new button_start_task_Listener());
- }
- private class button_start_task_Listener implements OnClickListener
- {
- public void onClick(View v)
- {
- Intent intent=new Intent(ActivityResultDemoActivity.this,SimpleTaskActivity.class);
- //关键点来了,使用startActivityForResult来启动
- startActivityForResult(intent, 100);
- }
- }
- /**
- * 复写onActivityResult,这个方法
- * 是要等到SimpleTaskActivity点了提交过后才会执行的
- */
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data)
- {
- //可以根据多个请求代码来作相应的操作
- if(20==resultCode)
- {
- String bookname=data.getExtras().getString("bookname");
- String booksale=data.getExtras().getString("booksale");
- TextView_result.setText("书籍名称:"+bookname+"书籍价钱"+booksale+"元");
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
- }
- package sn.len.actres;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- public class SimpleTaskActivity extends Activity
- {
- private EditText EditText_bookname;
- private EditText EditText_booksale;
- private Button Button_task_fulfill;
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main2);
- EditText_bookname=(EditText) findViewById(R.id.EditText_bookname);
- EditText_booksale=(EditText) findViewById(R.id.EditText_booksale);
- Button_task_fulfill=(Button) findViewById(R.id.Button_task_fulfill);
- Button_task_fulfill.setOnClickListener(new Button_task_fulfill_Listener());
- }
- private class Button_task_fulfill_Listener implements OnClickListener
- {
- public void onClick(View v)
- {
- String str_bookname=EditText_bookname.getText().toString();
- String str_booksale=EditText_booksale.getText().toString();
- //判断空,我就不判断了。。。。
- Intent data=new Intent();
- data.putExtra("bookname", str_bookname);
- data.putExtra("booksale", str_booksale);
- //请求代码可以自己设置,这里设置成20
- setResult(20, data);
- //关闭掉这个Activity
- finish();
- }
- }
- }