当前位置: 代码迷 >> Android >> android activity 互相传值
  详细解决方案

android activity 互相传值

热度:57   发布时间:2016-04-28 07:41:40.0
android activity 相互传值

1,传一个值的情况:

Main.activity

Pass value:

Intent intent = newIntent(MainActivity.this,SecondActivity.class);

intent.putExtra("Main","123");

startActivityForResult(intent, 0);

Get value from other activity

@Override

protectedvoid onActivityResult(int requestCode,int resultCode, Intent data) {

if (resultCode ==RESULT_OK)

{

Log.d("debug","result=" + data.getStringExtra("second"));

}

super.onActivityResult(requestCode, resultCode, data);

}


Test.activity

Get value:

Intent intent = getIntent();

final String num = intent.getStringExtra("Main");


Then pass value to main activity

Intent intent = newIntent();

intent.putExtra("second","This is Second Activity's value!");

setResult(RESULT_OK, intent);

finish();


如果传多个值的情况使用 Bundle

Pass value:

Home Activity:

Bundle bundle = new Bundle();


*字符、字符串、布尔、字节数组、浮点数等等,都可以传*/
bundle.putString("Name", "feng88724");
bundle.putBoolean("Ismale", true);


/*把bundle对象assign给Intent*/
intent.putExtras(bundle);


Get value:

Away Activity:

/*获取Intent中的Bundle对象*/
Bundle bundle = this.getIntent().getExtras();


*获取Bundle中的数据,注意类型和key*/
String name = bundle.getString("Name");
boolean ismale = bundle.getBoolean("Ismale");




  相关解决方案