标签:
1 package com.example.myact3; 2 3 import android.content.Intent; 4 import android.os.Bundle; 5 import android.support.v7.app.ActionBarActivity; 6 import android.view.View; 7 import android.view.View.OnClickListener; 8 import android.widget.Button; 9 import android.widget.TextView; 10 /** 11 * Android activity的回传数据 12 * @author shaobn 13 * 14 */ 15 public class MainActivity extends ActionBarActivity { 16 private Button button; 17 private TextView tv; 18 private static final int REQUEST = 1; 19 @Override 20 protected void onCreate(Bundle savedInstanceState) { 21 super.onCreate(savedInstanceState); 22 setContentView(R.layout.activity_main); 23 button = (Button)this.findViewById(R.id.button1); 24 tv = (TextView) this.findViewById(R.id.textView1); 25 button.setOnClickListener(new OnClickListener() { 26 27 @Override 28 public void onClick(View arg0) { 29 // TODO Auto-generated method stub 30 Intent intent = new Intent(MainActivity.this,MainActivity2.class); 31 intent.putExtra("text", tv.getText()); 32 //此方法发出请求携带自己的自已的请求码,方便回来时验证 33 startActivityForResult(intent,REQUEST); 34 } 35 }); 36 } 37 //requestCode 请求码,目的是和发出请求的activity的请求码相一致 38 //resultCode 响应码,目的是与本activity设置的响应码一致才接收数据。 39 //data 第二个页面传递过来的intent对象 40 @Override 41 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 42 // TODO Auto-generated method stub 43 super.onActivityResult(requestCode, resultCode, data); 44 if(resultCode==2){ 45 if(requestCode==REQUEST){ 46 String string = data.getStringExtra("response"); 47 this.tv.setText(string); 48 } 49 } 50 } 51 52 }
1 package com.example.myact3; 2 3 import android.content.Intent; 4 import android.os.Bundle; 5 import android.support.v7.app.ActionBarActivity; 6 import android.view.View; 7 import android.view.View.OnClickListener; 8 import android.widget.Button; 9 import android.widget.TextView; 10 11 public class MainActivity2 extends ActionBarActivity { 12 private TextView tv; 13 private Button button; 14 @Override 15 protected void onCreate(Bundle savedInstanceState) { 16 super.onCreate(savedInstanceState); 17 setContentView(R.layout.activity_main_activity2); 18 button = (Button) this.findViewById(R.id.button1); 19 tv = (TextView) this.findViewById(R.id.textView1); 20 tv.setText("olympic games"); 21 button.setOnClickListener(new OnClickListener() { 22 23 @Override 24 public void onClick(View arg0) { 25 // TODO Auto-generated method stub 26 Intent intent = new Intent(); 27 intent.putExtra("response", tv.getText()); 28 //回传给之前获得焦点的activity 29 setResult(2, intent); 30 //结束声明周期 31 finish(); 32 } 33 }); 34 35 } 36 }
标签:
原文地址:http://www.cnblogs.com/assassin666/p/4797814.html