You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin中Activity间数据传递问题:无法从MainActivity传值到WelcomeActivity

解决Xamarin Android Activity间数据传递失败的问题

我帮你排查下常见的问题点,一步步来解决:

1. 先检查传递数据的代码是否有两处关键错误

你给出的代码片段里有两个容易踩的坑:

  • 提前获取EditText文本:你现在是在按钮点击事件外面取的string name = myName.Text;,这时候用户还没输入内容,name肯定是空的!得把获取文本的逻辑放到点击事件内部。
  • PutExtra写法不完整:代码里welcome.PutExtra("name"...没写完,要把变量传进去,还要记得调用StartActivity启动目标Activity。

修正后的MainActivity核心代码

Button button = FindViewById<Button>(Resource.Id.send);
EditText myName = FindViewById<EditText>(Resource.Id.name);

button.Click += delegate {
    // 用户点击按钮时才读取输入的内容
    string name = myName.Text;
    var welcomeIntent = new Intent(this, typeof(Welcome));
    // 键"name"要和接收端完全一致
    welcomeIntent.PutExtra("name", name);
    // 必须调用这个方法启动Welcome Activity
    StartActivity(welcomeIntent);
};

2. 检查Welcome Activity的接收逻辑是否正确

很多时候问题出在接收端,要确保在OnCreate里正确读取Extra,而且键名要和传递时完全匹配(大小写敏感!):

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    SetContentView(Resource.Layout.Welcome);

    // 读取传递过来的名字
    string userName = Intent.GetStringExtra("name");
    
    // 比如找到TextView展示内容
    TextView welcomeMsg = FindViewById<TextView>(Resource.Id.welcome_message);
    if (!string.IsNullOrWhiteSpace(userName))
    {
        welcomeMsg.Text = $"Hey {userName}, welcome aboard!";
    }
}

3. 确认Welcome Activity已经注册到Manifest

虽然Xamarin一般会自动注册,但如果是手动创建的Activity,可能会漏掉。打开AndroidManifest.xml,确保有这条注册项:

<activity android:name=".Welcome" />

4. 核对布局文件里的ID是否匹配

检查Main.axml里的EditText ID是不是@+id/name,Welcome.axml里的TextView ID是不是你代码里用的那个,ID不匹配的话会导致控件找不到,数据也没法展示。

如果以上都排查过还是不行,试试清理项目后重新编译,有时候缓存会导致一些莫名的问题~

内容的提问来源于stack exchange,提问作者Roy Henriquez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:57:13