package com.example.myact3; import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
/**
* Android activity的回传数据
* @author shaobn
*
*/
public class MainActivity extends ActionBarActivity {
private Button button;
private TextView tv;
private static final int REQUEST = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)this.findViewById(R.id.button1);
tv = (TextView) this.findViewById(R.id.textView1);
button.setOnClickListener(new OnClickListener() { @Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("text", tv.getText());
//此方法发出请求携带自己的自已的请求码,方便回来时验证
startActivityForResult(intent,REQUEST);
}
});
}
//requestCode 请求码,目的是和发出请求的activity的请求码相一致
//resultCode 响应码,目的是与本activity设置的响应码一致才接收数据。
//data 第二个页面传递过来的intent对象
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==2){
if(requestCode==REQUEST){
String string = data.getStringExtra("response");
this.tv.setText(string);
}
}
} }
package com.example.myact3; import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView; public class MainActivity2 extends ActionBarActivity {
private TextView tv;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
button = (Button) this.findViewById(R.id.button1);
tv = (TextView) this.findViewById(R.id.textView1);
tv.setText("olympic games");
button.setOnClickListener(new OnClickListener() { @Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.putExtra("response", tv.getText());
//回传给之前获得焦点的activity
setResult(2, intent);
//结束声明周期
finish();
}
}); }
}
第二个页面的可以new Intent(),那默认使用的就是之前activit的请求码。