跳轉與資料傳遞
阿新 • • 發佈:2020-12-20
java程式碼
1 package com.example.myapplication; 2 3 import androidx.appcompat.app.AppCompatActivity; 4 5 import android.content.Intent; 6 import android.os.Bundle; 7 import android.view.View; 8 import android.widget.Button; 9 10 publicclassAActivity extends AppCompatActivity { 11 privateButton btn_a;12 13 @Override 14 protectedvoidonCreate(Bundle savedInstanceState) { 15 super.onCreate(savedInstanceState); 16 setContentView(R.layout.activity_a); 17 btn_a=findViewById(R.id.btn_a); 18 btn_a.setOnClickListener(newView.OnClickListener() { 19 @Override 20 publicvoidonClick(View view) { 21 Intent intent=newIntent(AActivity.this,BActivity.class); 22 Bundle bundle=newBundle(); 23 bundle.putString("name","zhangsan"); 24 bundle.putInt("number",20); 25 intent.putExtras(bundle); 26 startActivity(intent); 27 } 28 }); 29 } 30 }
介面一 xml
1 <?xml version="1.0"encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical"> 6 <Button 7 android:id="@+id/btn_a" 8 android:layout_marginTop="200dp" 9 android:layout_width="wrap_content" 10 android:layout_height="wrap_content" 11 android:text="跳轉到下一介面" 12 android:layout_gravity="center"/> 13 <TextView 14 android:layout_marginTop="50dp" 15 android:layout_width="match_parent" 16 android:layout_height="wrap_content" 17 android:text="點選跳轉到下一介面 這裡會傳遞兩個數:zhangsan,20" 18 android:textSize="20dp" 19 /> 20 </LinearLayout>
介面二java
1 package com.example.myapplication; 2 3 import androidx.appcompat.app.AppCompatActivity; 4 5 import android.os.Bundle; 6 import android.widget.TextView; 7 8 publicclassBActivity extends AppCompatActivity { 9 privateTextView tv_b; 10 @Override 11 protectedvoidonCreate(Bundle savedInstanceState) { 12 super.onCreate(savedInstanceState); 13 setContentView(R.layout.activity_b); 14 tv_b=findViewById(R.id.tv_b); 15 Bundle bundle=getIntent().getExtras(); 16 String name = bundle.getString("name"); 17 intnumber = bundle.getInt("number"); 18 19 tv_b.setText(name+","+number); 20 } 21 }
介面三xml
1 <?xml version="1.0"encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:orientation="vertical"> 7 8 <TextView 9 android:id="@+id/tv_b" 10 android:layout_marginTop="200dp" 11 android:layout_width="match_parent" 12 android:layout_height="wrap_content" 13 android:gravity="center" 14 android:textColor="#000000" 15 android:textSize="20dp" 16 /> 17 18 </LinearLayout>