使用Bundle傳遞複雜資料
阿新 • • 發佈:2019-02-07
第一種方法
1、在第一個activity中
<span style="font-size:18px;"><span style="white-space:pre"> </span>Button start = (Button)findViewById(R.id.toSecond); start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this,SecondActivity.class); Bundle data = new Bundle(); data.putString("name","Jack"); data.putInt("age",23); i.putExtras(data); startActivity(i); } });</span>
2、在第二個activity中進行資料讀取
<span style="font-size:18px;"><span style="font-size:18px;">Intent i = getIntent(); Bundle data = i.getExtras(); TextView textView = (TextView) findViewById(R.id.textView); textView.setText(String.format("name=%s,age=%d,name1=%s",data.getString("name"),data.getInt("age"),data.getString("name1","LJaer")));</span></span>
通過向intent中傳入一個Bundle型別的字串進行資料傳遞,name1 沒有數值,進行預設LJaer設定
第二種方法
1、在第一個activity中
<span style="font-size:18px;">start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this,SecondActivity.class); Bundle data = new Bundle(); data.putString("name","Jack"); data.putInt("age",23); //i.putExtras(data); i.putExtra("info",data); startActivity(i); } });</span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;">2、在第二個activity中</span>
<pre name="code" class="java"><span style="font-size:18px;">Intent i = getIntent();
//Bundle data = i.getExtras();
Bundle data = i.getBundleExtra("info");
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(String.format("name=%s,age=%d,name1=%s",data.getString("name"),data.getInt("age"),data.getString("name1","LJaer")));</span>