使用
PutExtra()发送数据,GetStringExtra()接收数据,??空合并运算符做兜底默认值。
1、主页面布局 activity_main.axml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--注意id:@+id/edittext -->
<EditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="请输入内容"/>
<Button
android:text="提交"
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>Code language: HTML, XML (xml)
2、第二个页面布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--接收数据展示,id:textview1-->
<TextView
android:id="@+id/textview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:text="返回首页"
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>Code language: HTML, XML (xml)
3、MainActivity.cs 发送数据页面
using Android.App;
using Android.OS;
using Android.Widget;
using Android.Content;
namespace TestPass
{
[Activity(Label = "MainActivity")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
//绑定按钮点击事件
Button button = FindViewById<Button>(Resource.Id.button1);
button.Click += Button_Click;
}
private void Button_Click(object sender, EventArgs e)
{
//1. 创建Intent,跳转至SecondScreen
var second = new Intent(this, typeof(SecondScreen));
//2. PutExtra传递字符串,key="name"
string inputText = FindViewById<EditText>(Resource.Id.edittext).Text;
second.PutExtra("name", inputText);
//3. 启动第二个Activity
StartActivity(second);
}
}
}Code language: HTML, XML (xml)
4、SecondScreen.cs 接收数据页面
using Android.App;
using Android.OS;
using Android.Widget;
using Android.Content;
namespace TestPass
{
[Activity(Label = "SecondScreen")]
public class SecondScreen : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.content_main);
//接收Intent传递过来的数据 并且给控件赋值
// ?? "出现错误":如果拿到null,就显示兜底文本
FindViewById<TextView>(Resource.Id.textview1).Text
= Intent.GetStringExtra("name") ?? "出现错误";
//返回首页按钮
Button button = FindViewById<Button>(Resource.Id.button1);
button.Click += Button_Click;
}
private void Button_Click(object sender, EventArgs e)
{
//回到主页面
StartActivity(typeof(MainActivity));
}
}
}Code language: HTML, XML (xml)
Previous: 活动(Activity)创建与页面跳转