如何在Android應用程式中Activity之間傳遞資料?


本例演示如何在Android應用程式中Activity之間傳遞資料。

步驟 1 − 在Android Studio中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。

步驟 2 − 將以下程式碼新增到res/layout/activity_main.xml。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:id="@+id/activity_first"
   android:paddingTop="60dp"
   tools:context=".FirstActivity">
   <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical">
      <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:paddingLeft="10sp">
         <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.25"/>
         <EditText
            android:id="@+id/editTxtName"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.75"
            android:ems="10" />
      </LinearLayout>
      <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:paddingLeft="10sp"
         android:paddingTop="16dp">
         <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.25" />
         <Spinner
            android:id="@+id/ageGroupSpinner"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="0.75"/>
      </LinearLayout>
      <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:paddingTop="16dp">
         <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.50" />
         <Button
            android:id="@+id/btnSubmit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.20"/>
      </LinearLayout>
   </LinearLayout>
</RelativeLayout>

步驟 3 − 將以下程式碼新增到res/layout/activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:id="@+id/activity_second"
   android:paddingTop="60dp">
   <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical">
      <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:paddingLeft="10sp">
         <TextView
            android:id="@+id/displayMsg"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.25" />
      </LinearLayout>
   </LinearLayout>
</RelativeLayout>

步驟 4 − 將以下程式碼新增到src/MainActivity.java

package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class FirstActivity extends AppCompatActivity {
   Button btnSubmit = null;
   EditText editTxtName = null;
   private static final String STING_EMPTY = "";
   private static int ageGroup = 0;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_first);
      btnSubmit = (Button) findViewById(R.id.btnSubmit);
      btnSubmit.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            editTxtName = (EditText) findViewById(R.id.editTxtName);
            if (STING_EMPTY.equals(editTxtName.getText().toString())) {
               Toast.makeText(FirstActivity.this, "Name Cannot be empty!",
               Toast.LENGTH_LONG).show();
            } else {
               Spinner ageGroupSpinner = (Spinner)findViewById(R.id.ageGroupSpinner);
               ageGroupSpinner.setOnItemSelectedListener(
               new AdapterView.OnItemSelectedListener() {
                  @Override
                  public void onItemSelected(AdapterView<?> adapterView, View view,
                  int i, long l) {
                     //set the corresponding age group when the user changes
                     // the age group from dropdown
                     ageGroup = i;
                  }
                  @Override
                  public void onNothingSelected(AdapterView<?> adapterView) {
                  }
               });
               //Create a new intent for the SecondActivity
               Intent i = new Intent(FirstActivity.this,SecondActivity.class);
               //Populate the input values in a bundle and pass it to SecondActivity
               Bundle b = new Bundle();
               b.putString("name",editTxtName.getText().toString());
               b.putInt("ageGroup",ageGroup);
               //Set the userBundle to the intent
               i.putExtra("userBundle",b);
               startActivity(i);
            }
         }
      });
   }
}

步驟 5 − 將以下程式碼新增到src/SecondActivity.java

package com.example.sample;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_second);
      //get the passed intent
      Intent i = getIntent();
      //get the bundle stored inside the intent
      Bundle b = i.getBundleExtra("userBundle");
      TextView displayMsg = (TextView) findViewById(R.id.displayMsg);
      String message = "Hi, " + b.getString("name") + " ";
      int ageGroup = b.getInt("ageGroup");
      switch (ageGroup){
         case 0: message = message + "Enjoy your life";
         break;
         case 1: message = message + "Don't take life too seriously.. Have fun!";
         break;
         case 2: message = message + "Celebrate your life with old memories!";
         break;
      }
      displayMsg.setText(message);
   }
}

步驟 6 − 將以下程式碼新增到Manifests/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".FirstActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      <activity android:name=".SecondActivity"></activity>
   </application>
</manifest>

讓我們嘗試執行您的應用程式。我假設您已將實際的Android移動裝置連線到計算機。要從Android Studio執行應用程式,請開啟專案的一個Activity檔案,然後單擊執行  工具欄中的圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 –

點選 這裡 下載專案程式碼。

更新於:2020年7月7日

瀏覽量:118

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告