Ø在实际的应用中,我们不仅仅要向Activity传递数据,而且要从Activity中返回数据,虽然返回数据和传递数据类似,也可以采用前面4种方法,但是一般建议采用Intent对象的方式来返回数据,使用这种方式返回数据,需要使用startActivityForResult方法来显示Activity。
Ø案例一
package com.android.myintent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Main extends Activity {
/** Called when the activity is first created. */
private Button button;
private final static int REQUESTCODE = 1;//返回的结果码
private EditText one,two,result;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) this.findViewById(R.id.button);
one = (EditText)this.findViewById(R.id.one);
two = (EditText)this.findViewById(R.id.two);
result = (EditText)this.findViewById(R.id.result);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int a = Integer.parseInt(one.getText().toString());
int b = Integer.parseInt(two.getText().toString());
Intent intent = new Intent(Main.this, OtherActivity.class);
intent.putExtra("a", a);
intent.putExtra("b", b);
//启动Intent
startActivityForResult(intent, REQUESTCODE);// 表示可以返回结果
}
});
}
@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==REQUESTCODE){
int three = data.getIntExtra("three", 0);
result.setText(String.valueOf(three));
}
}
}
}
package com.android.myintent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class OtherActivity extends Activity {
private Button button;
private TextView textView;
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
button = (Button)this.findViewById(R.id.button2);
textView = (TextView)this.findViewById(R.id.msg);
editText = (EditText)this.findViewById(R.id.three);
Intent intent = getIntent();
int a = intent.getIntExtra("a", 0);
int b = intent.getIntExtra("b", 0);
textView.setText(a+" + "+b+" = "+" ? ");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
int three = Integer.parseInt(editText.getText().toString());
intent.putExtra("three", three);
//通过Intent对象返回结果,setResult方法,
setResult(2, intent);
finish();//结束当前的Activity的生命周期。
}
});
}
}