当我们在一个A(Activity)跳转到另外一个B(Activity)时,再由B返回A时,A如何接受返回的数据。
我们在B页面加了一个输入框和按钮,当输入数据,点击按钮返回信息到A页面,先来看B页面Activity代码
package com.example.testapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class BMainActivity extends Activity {
private TextView t;
private EditText t1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmain);
t = (TextView) findViewById(R.id.tv);
Intent i = getIntent();
// User user = (User) i.getSerializableExtra("user");
User user = (User) i.getParcelableExtra("user");
t.setText("name=" + user.getName() + ",age=" + user.getAge());
t1 = (EditText) findViewById(R.id.editText1);
findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent();
i.putExtra("data", t1.getText().toString());
setResult(1, i);
finish();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bmain, menu);
return true;
}
}
代码中为按钮增加一个事件,并使用setResult方法返回Intent对象,然后调用finish方法
点击按钮后返回到A页面(这个按钮是如何定位上一个页面的还在调研…)
A的Activity代码如下
package com.example.testapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class AMainActivity extends Activity {
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amain);
editText = (EditText) findViewById(R.id.editText1);
findViewById(R.id.button1).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(AMainActivity.this,
BMainActivity.class);
i.putExtra("user", new User("lijingwei", 25));
// startActivity(i);
startActivityForResult(i, 0);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
editText.setText(data.getStringExtra("data"));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.amain, menu);
return true;
}
}
注意,我们将startActivity(i)改成了startActivityForResult(i,0),并且重写了protected void onActivityResult(int requestCode, int resultCode, Intent data)方法。用来接收B返回的数据。
时间: 2024-09-30 06:39:17