如何将值从活动传递到Kotlin中的另一个活动 [英] How to pass the values from activity to another activity in kotlin

查看:343
本文介绍了如何将值从活动传递到Kotlin中的另一个活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在学习Kotlin进行Android开发时,我现在正在尝试诸如hello world之类的基本程序,以及如何从一个活动导航到另一个活动,这没有问题.

As I'm learning Kotlin for Android development, I'm now trying the basic programs like hello world and how to navigate from one activity to another activity , there is no issue in this.

我担心的是,当我从一个活动转移到另一个活动时,它工作正常,但是我不知道如何在活动之间传递值.

My concern is when I move from one activity to another activity it works fine but I do not know how to pass the values between the activities.

我很累在一个活动中设置值,而在另一个活动中却无法使用.

I tired to set the values in one activity and retrieved in another activity it does not work.

请参见下面的代码段

这是我的主要活动,我从编辑文本中获取用户名和密码并将其设置为意图:

This is my main activity where I take the username and password from edit text and setting to the intent:

class MainActivity : AppCompatActivity() {
    val userName = null
    val password = null
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    button.setOnClickListener {
        val intent = Intent(this@MainActivity,SecondActivity::class.java);
        var userName = username.textø
        var password = password_field.text
        intent.putExtra("Username", userName)
        intent.putExtra("Password", password)
        startActivity(intent);
    }
}

}

这是我的第二项活动,我必须从主要活动中接收值

This is my second activity where I have to receive values from the main activity

class SecondActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
        var strUser: String = intent.getStringExtra("Username")
        var strPassword: String = intent.getStringExtra("Password")
        user_name.setText("Seelan")
        passwor_print.setText("Seelan")

    }
}

如果我不是故意的话,请问我是否有其他方法可以在Kotlin中做到这一点.

Please guide me how to do this, whether if I have some other way to do this in Kotlin if not by intent.

推荐答案

从HomeActivity发送值

Send value from HomeActivity

val intent = Intent(this@HomeActivity,ProfileActivity::class.java)
intent.putExtra("Username","John Doe")
startActivity(intent)

在ProfileActivity中获取值

Get values in ProfileActivity

val profileName=intent.getStringExtra("Username")

这篇关于如何将值从活动传递到Kotlin中的另一个活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆