在Android中,一个界面被称为一个activity,在两个界面之间通信,采用的是使用一个中间传话者(即Intent类)的模式,而不是直接通信。
下面演示如何实现两个activity之间的通信。
信息的发起者为Test,接收者为Target,代码如下:
Test类:
1 package com.example.testsend; 2 3 import android.content.Intent; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.view.View; 7 8 public class Test extends AppCompatActivity { 9 10 @Override 11 protected void onCreate(Bundle savedInstanceState) { 12 super.onCreate(savedInstanceState); 13 setContentView(R.layout.activity_test); 14 15 findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { 16 @Override 17 public void onClick(View view) { 18 Intent intent=new Intent(Test.this,Target.class); 19 intent.putExtra("data","hi"); 20 startActivity(intent); 21 } 22 }); 23 24 } 25 }
activity_test.xml:
1 <?xml version="1.0" encoding="utf-8"?> 2 <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 tools:context="com.example.testsend.Test"> 8 9 <Button 10 android:id="@+id/button" 11 android:layout_width="wrap_content" 12 android:layout_height="wrap_content" 13 android:text="Send" 14 app:layout_constraintBottom_toBottomOf="parent" 15 app:layout_constraintLeft_toLeftOf="parent" 16 app:layout_constraintRight_toRightOf="parent" 17 app:layout_constraintTop_toTopOf="parent" /> 18 19 </android.support.constraint.ConstraintLayout>
Target类:
1 package com.example.testsend; 2 3 import android.content.Intent; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.widget.TextView; 7 8 public class Target extends AppCompatActivity { 9 private TextView textview; 10 @Override 11 protected void onCreate(Bundle savedInstanceState) { 12 super.onCreate(savedInstanceState); 13 setContentView(R.layout.activity_target); 14 15 Intent intent =getIntent(); 16 textview=(TextView)findViewById(R.id.textview); 17 textview.setText(intent.getStringExtra("data")); 18 19 } 20 }
activity_target.xml:
1 <?xml version="1.0" encoding="utf-8"?> 2 <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 tools:context="com.example.testsend.Target"> 8 9 <TextView 10 android:id="@+id/textview" 11 android:layout_width="wrap_content" 12 android:layout_height="wrap_content" 13 /> 14 15 </android.support.constraint.ConstraintLayout>
结果如图:
时间: 2024-10-13 16:19:42