Android-Intent实现数据传递
在activityA中使用putExtras(bundle)传递数据,在activityB中使用getExtras()获取数据
MainActivity.java及其xml
package com.example.intentactivity;import androidx.appcompat.app.AppCompatActivity;import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;public class MainActivity extends AppCompatActivity {Button go;EditText txt1;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void go(View view){go = findViewById(R.id.go);txt1 = findViewById(R.id.text1);Intent intent = new Intent(this,MainActivity2.class);Bundle bundle = new Bundle();bundle.putString("txt1",txt1.getText().toString());intent.putExtras(bundle);startActivity(intent);}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:orientation="vertical"><EditTextandroid:id="@+id/text1"android:layout_width="match_parent"android:layout_height="wrap_content"/><Buttonandroid:id="@+id/go"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="GO"android:textSize="20sp"android:onClick="go"/>
</LinearLayout>
Mainactivity2.java和xml
package com.example.intentactivity;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;
import android.widget.TextView;public class MainActivity2 extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main2);TextView text = findViewById(R.id.text);Bundle receive = this.getIntent().getExtras();String text1 = receive.getString("txt1");text.setText(text1+", this is the passion");}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:orientation="vertical"tools:context=".MainActivity2"><TextViewandroid:id="@+id/text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text=""android:textSize="20sp"android:textColor="@color/purple_200"/><ImageViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/replace"/></LinearLayout>