1.使用Intent进行传输
//发送数据的Activity class button implements OnClickListener{ @Override public void onClick(View v) { // TODO Auto-generated method stub String ET_1String = ET_1.getText().toString(); //得到文本输入框中的文本 String ET_2String = ET_2.getText().toString(); Intent intent = new Intent(); intent.putExtra("one",ET_1String); //进行参数的传递(“参数名字”,参数) intent.putExtra("two",ET_2String); intent.setClass(MainActivity.this, result.class); MainActivity.this.startActivity(intent); } } //接收数据的Activity public class result extends Activity{ private TextView resulTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.result); resulTextView = (TextView)findViewById(R.id.TV_1); Intent intent = getIntent(); //定义接收数据的Intent String oneString = intent.getStringExtra("one"); String twoString = intent.getStringExtra("two"); int a = Integer.parseInt(oneString); //进行计算之前要进行强制类型转换 int b = Integer.parseInt(twoString); int c = a * b; resulTextView.setText(c + ""); //要加一个空字符对int类型进行强制类型转换 } }
2.使用静态变量进行传递
1.主界面(发送数据的Activity) class ButtonListener implements android.view.View.OnClickListener{ @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setClass(MainActivity.this, OtherActivity.class); OtherActivity.nameString = "zhao"; startActivity(intent); } } 2.接受数据Activity public class OtherActivity extends Activity{ //定义静态变量 public static String nameString; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.otheractivity); System.out.println("nameString-------->"+nameString); } }
3.利用setResult进行数据传输
//1.要关闭的页面 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.otheractivity); Intent intent = this.getIntent(); intent.putExtra("tel", 12345); //设置requestCode和带有数据的intent对象 OtherActivity.this.setResult(3, intent); //马上关闭Activity this.finish(); } //2.上面的页面关闭时,此页面进行数据的接收 class ButtonListener implements android.view.View.OnClickListener{ @Override public void onClick(View arg0) { Intent intent = new Intent(); intent.setClass(MainActivity.this, OtherActivity.class); //与普通的start方法不同,需要设置requestCode startActivityForResult(intent, 1); } } //如果要进行此操作,需要在数据接收页面中复写activity的onActivityResul()方法 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); int tel = 0; //根据返回码resultCode来判断下一步进行的业务代码 if(resultCode==3){ tel = data.getIntExtra("tel", 0); } Log.i(TAG, "tel--------->"+String.valueOf(tel)); }