简体   繁体   中英

Kotlin synthetic view in activity gets null when a custom dialog is shown and dismissed

I am updating a view in activity's onCreate method which is working fine using kotlin extension as stated below.

Activity's onCreate

import kotlinx.android.synthetic.main.activity_otpverification.*

     override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_otpverification)
            tvContactNumber.text = getString(R.string.dual_string_value_placeholder)
        }

Then at a click of a button I am showing a custom dialog for performing some action. When the dialog is dismissed I update the same textView in activity with the data sent from dialog, but the view tvContact is throwing null exception.

Activity's onClick

override fun onClick(p0: View?) {
    when (p0?.id) {
        R.id.ivEdit -> {
            object : ChangeNumberDialog(this) {
                override fun onSubmitClicked(number: String) {
                    tvContactNumber.text =number
                }
            }.show()
        }
    }
}

onSubmitClicked is an abstract method in the dialog which is triggered when the dialog is dismissed.

Error from logcat :

    java.lang.IllegalStateException: tvContactNumber must not be null
            at com.beat.em.ui.activities.OTPVerificationActivity$onClick$1.onSubmitClicked
(OTPVerificationActivity.kt:211)

onCreate and onClick methods from the ChangeNumberDialog :

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val view = layoutInflater.inflate(R.layout.dialog_change_number, null, false)
        setContentView(view)
        setCanceledOnTouchOutside(false)
        setCancelable(true)
        tvSubmit.setOnClickListener(this)
    }

  override fun onClick(view: View) {
    when (view.id) {
        R.id.tvSubmit -> {
            onSubmitClicked(etNumber.text.toString().trim())
            dismiss()
          }
       }
  }

I have just started using kotlin extension and not able to understand the cause. Help appreciated.

您尝试访问的变量在另一个范围内,尝试向视图添加显式范围,即

this@YourActivity.tvContactNumber.text = number

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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