歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android教程:使用Bundle在Activity之間傳遞數據

Android教程:使用Bundle在Activity之間傳遞數據

日期:2017/3/1 10:24:44   编辑:Linux編程

Bundle可能過put****()方法添加各種類型的數據,Intent也可以通過putExtras(Bundle)將數據添加進去,然後通過startActivity()跳到下一下Activity的時候就把數據也傳到下一個Activity了。

  1. package com.intent;
  2. import Android.app.Activity;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.view.View.OnClickListener;
  7. import android.widget.Button;
  8. public class TestIntentActivity extends Activity {
  9. /** Called when the activity is first created. */
  10. @Override
  11. public void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.main);
  14. Button button = (Button)this.findViewById(R.id.button);
  15. button.setOnClickListener(new OnClickListener() {
  16. public void onClick(View v) {
  17. Intent intent = new Intent(TestIntentActivity.this,SecondActivity.class);
  18. Bundle bundle = new Bundle();
  19. bundle.putString("key_name", "name");
  20. bundle.putString("key_age", "age");
  21. intent.putExtras(bundle);
  22. startActivity(intent);
  23. }
  24. });
  25. }
  26. }

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical" >
  6. <Button
  7. android:layout_width="fill_parent"
  8. android:layout_height="wrap_content"
  9. android:text="@string/intent"
  10. android:id="@+id/button" />
  11. </LinearLayout>

  1. package com.intent;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.widget.TextView;
  5. public class SecondActivity extends Activity{
  6. @Override
  7. protected void onCreate(Bundle savedInstanceState) {
  8. super.onCreate(savedInstanceState);
  9. setContentView(R.layout.second);
  10. TextView tv1 = (TextView)this.findViewById(R.id.tv1);
  11. TextView tv2 = (TextView)this.findViewById(R.id.tv2);
  12. Bundle bundle = this.getIntent().getExtras();
  13. tv1.setText(bundle.getString("key_name"));
  14. tv2.setText(bundle.getString("key_age"));
  15. }
  16. }
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical" >
  6. <TextView android:layout_width="fill_parent"
  7. android:layout_height="wrap_content"
  8. android:id="@+id/tv1"/>
  9. <TextView android:layout_width="fill_parent"
  10. android:layout_height="wrap_content"
  11. android:id="@+id/tv2"/>
  12. </LinearLayout>

最後將新的Activity添加到manifest.xml裡面就可以了

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved