当前位置:操作系统 > 安卓/Android >>

android activity 相互传值

1,传一个值的情况:
 
Main.activity
 
Pass value:
 
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("Main", "123");
startActivityForResult(intent, 0);
Get value from other activity
@Override
protected void 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 = new Intent();
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");
 
补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,