Home > Blockchain >  change text in android studio using viewBinding
change text in android studio using viewBinding

Time:06-11

I don't know why text is not changing in the BirthdayGreetingActivity. No error is coming but it's not changing text. I checked(by Logcat) that name has came successfully to BirthdayGreetingActivity.kt from MainActivity.kt.

I guess that this [binding.birthdayGreeting.text = "Happy Birthday $name"] line in BirthdayGreetingActivity.kt is not working properly.

MainActivity.kt --

package com.example.firstapp

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.example.firstapp.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }
    fun createBirthdayCard(view: View){
        val name = binding.nameInput.editableText.toString()
//        Toast.makeText(this,"Name is $name",Toast.LENGTH_SHORT).show()

        val intent = Intent(this,BirthdayGreetingActivity::class.java)
        intent.putExtra(BirthdayGreetingActivity.NAME_EXTRA,name)
        startActivity(intent)

    }
}

BirthdayGreetingActivity.kt --

package com.example.firstapp

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.example.firstapp.databinding.ActivityBirthdayGreetingBinding

class BirthdayGreetingActivity : AppCompatActivity() {

    private lateinit var binding: ActivityBirthdayGreetingBinding

    companion object{
        const val NAME_EXTRA ="name_extra"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityBirthdayGreetingBinding.inflate(layoutInflater)
        setContentView(R.layout.activity_birthday_greeting)

        val name = intent.getStringExtra(NAME_EXTRA)
//        val greet = binding.birthdayGreeting.editableText.toString()
//        print(name)
//        if (name != null) {
//            Log.d("greet = ",binding.birthdayGreeting.editableText.toString())
//        }
        binding.birthdayGreeting.text = "Happy Birthday $name" [maybe something wrong here]
    }
}

:) :) Thanks for spending your valuable time to help me :) :)

CodePudding user response:

On BirthdayGreetingActivity you are passing the layout ID for setContentView, instead you must pass the binding.root, just like you did on MainActivity...

Change this line:

setContentView(R.layout.activity_birthday_greeting)

To:

setContentView(binding.root)
  • Related