Kotlin android extension


#1

Hello. I have this code:

private fun showWeightPickerDialog() {
        NumberPickerBottomSheet().apply {
            init(R.string.height_picker_title,
                    intArrayOf(1, 2, 3, 4, 5, 6, 7)
            )

            onDismiss = {
                setWeight(it.toString())
            }
            show(this@UserInfoGatherActivity.supportFragmentManager, this.tag)
        }
    }

    private fun setWeight(weight: String) {
        targetWeigth.setText(weight.toString())
    }

If set the text of targetWeight directly inside onDismiss, the compiler throws an exception at runtime saying it cannot setText to a null object reference. My guess is that, android extensions pick the context of the BottomSheet and try to find targetWeigth, and it won’t find because that view is present in the activity layout not in the fragment. Is there any workaround for this? Is this a bug?

TLDR: Code works like this. Get rid of setWeight and call setText directly can’t find the textview


#2

Please use qualified this.

this@MyActivity.targetWeigth.setText(...)

Also, is the kotlinx.android.synthetic.<variant>.<layout>.view (note the view part) package imported? If synthetic properties with the View receiver are not what you wanted to use here, you can just delete the import.