How to pass the values from activity to another activity in kotlin

前端 未结 7 852
北恋
北恋 2020-12-03 10:13

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

相关标签:
7条回答
  • 2020-12-03 10:51
        //On Click on Button 
    
        var but = findViewById<Button>(R.id.buttionActivity_two) as Button
    
                but.setOnClickListener {
        //Define intent 
                    var intent = Intent(applicationContext,MainActivity::class.java)
    // Here "first" is key and 123 is value                
    intent.putExtra("first",123)
                    startActivity(intent)
    
                }
    
            }
    
    // If Get In Into Other Activity
    var Intent1: Intent
    Intent1= getIntent()
    //Here first is key and 0 is default value
          var obj :Int  =  Intent1.getIntExtra("first",0);
          Log.d("mytag","VAlue is==>"+obj)
    
    0 讨论(0)
  • 2020-12-03 10:52

    In Kotlin, you can pass the data simply by using the Intents. You can directly put your data in intent or you can write those data in bundle and send that bundle to another activity using the intent.

    val intent = Intent(this@HomeActivity,ProfileActivity::class.java);
    intent.putExtra("profileName", "John Doe")
    var b = Bundle()
    b.putBoolean("isActive", true)
    intent.putExtras(b)
    startActivity(intent);
    
    0 讨论(0)
  • 2020-12-03 11:02

    Send value from HomeActivity

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

    Get values in ProfileActivity

    val profileName=intent.getStringExtra("Username")
    
    0 讨论(0)
  • 2020-12-03 11:04

    You can just access the value without using extras or intent. Simply use companion object in MainActivity:

        companion object{
            val userName: String = String()
            val password: String = String()
        }
    

    In SecondActivity:

        var strUser: String = MainActivity.username
        var strPassword: String = MainActivity.password
    

    And you can access the values from multiple activities easily.

    0 讨论(0)
  • 2020-12-03 11:12

    I'm on mobile, you must test by yourself.

    Try to make a CharSequence to a String in MainActivity , you have put a CharSequence rather than a String, for example:

    var userName = username.text.toString()
    var password = password_field.text.toString()
    
    0 讨论(0)
  • 2020-12-03 11:12

    You can simply use the intents and bundle to send data from one activity to another activity.

    val intent = Intent(this@OneActivity,TwoActivity::class.java);
    intent.putExtra("username", userName)
    startActivity(intent);
    
    0 讨论(0)
提交回复
热议问题