首页 > 代码库 > Android activity 参数传递
Android activity 参数传递
Android activity 参数传递 经过网上的资料收集终于测试成功,可以两个Activity 之间相互传递参数。先将部分代码帖出来(关键代码已注释),仅供参考。
第一个activity:activity_main
导入相关包
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.content.Intent;
import android.app.Activity;
button 按钮传递参数:
private Button bt;
private TextView tw1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt=(Button)findViewById(R.id.btnBack);
tw1=(TextView)findViewById(R.id.edtRec);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent it= new Intent();
//传递参数
it.putExtra("name", tw1.getText().toString());
it.setClass(MainActivity.this, ShowInfo.class);
// startActivity(it); //不接收返回值
startActivityForResult(it, 1); //接收返回值 这里参数必须>0 否则onActivityResult无法执行
// MainActivity.this.finish(); //终止Activity
}
});
}
接收返回参数:前面的按钮必须设置为startActivityForResult(it, 1); //接收返回值
/**
* 接收带有返回值的Activity方法
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Log.i("Main", "requestCode:"+requestCode+"resultCode:"+resultCode);
//这里 requestCode=1,resultCode=-1
if(requestCode == 1){
tw1.setText(data.getStringExtra("return"));
}
// tw1.setText(data.getStringExtra("return"));
}
第二个activity ShowInfo:
private TextView tv1;
private Button btnBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_info);
//新页面接收数据
Intent intent=this.getIntent();
String name=intent.getStringExtra("name");
Log.i("获取到的name值为",name);
tv1 = (TextView)findViewById( R.id.edtRec );
tv1.setText("传过来的值为:"+name);
btnBack=(Button)findViewById(R.id.btnBack);//定义返回按钮
btnBack.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) //返回按钮传递参数给主页面
{
Intent intent=new Intent();
intent.putExtra("return", tv1.getText().toString()); //传递参数到return
setResult(RESULT_OK, intent);
finish(); //关闭当前activity
}
});
}
本文出自 “我的地盘我做主” 博客,请务必保留此出处http://clchyj.blog.51cto.com/2379532/1568328
Android activity 参数传递