繁体   English   中英

如何通过意图将字符串值从一个活动发送到另一个活动?

[英]How to send String values from one activity to another through intent?

如何将用户放在 StartActivity 中的 editText 中的值发送到 Second Activity 中的 textView3? 我本质上是在 StartActivity 中询问用户他的名字,然后在 SecondActivity 中打印“你的名字是 ___”。

我确实尝试使用然后在 SecondActivity 中但它显示为 null 我该怎么办?

开始活动::

    button.setOnClickListener 
    {
        val name = editText.text.toString()
        val intent2 = Intent (this, SecondActivity::class.java)

        intent.putExtra("name", name)
        startActivity(intent2)

    }

第二个活动::

    override fun onCreate(savedInstanceState: Bundle?) 
    {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_second)

      val name2 = intent.getStringExtra("name")
      textView3.text = name2
    }

错误是它打印“您的姓名为空”。 enter code here

这看起来像是Kotlin帮助您进行的打字错误。 您要启动的意图的名称是intent2 ,但是您要在intent添加“名称”字符串。 这是可能的,因为Kotlin允许您访问getIntent()的结果(即用于启动当前活动的Intent对象),就好像它是一个属性一样。

更改此行以使用intent2 ,它应该都可以开始工作:

intent2.putExtra("name", name)

请正确检查代码。 您定义了其他变量名称。

它要么是intentputExtraputExtra的变量名putExtraintent2

button.setOnClickListener 
    {
        val name = editText.text.toString()
        val intent = Intent(this, SecondActivity::class.java)
        intent.putExtra("name", name)
        startActivity(intent2)

    }

开启第二项活动:

val name2 = intent.getStringExtra("name")
textView3.text = name2

intent.putExtra("name", name)更改为intent2.putExtra("name", name)

注意:只要您在范围内没有可变intent Kotlin扩展从getIntent()获取intent值,这是您先前的意图。 这就是为什么您错过了编译错误的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM