Error using Kotlin Android Extensions

1

I'm using these extensions and everything works great, but I've noticed that sometimes does not perform the bind correctly, in modules such as Adapters, ViewHolders and this time in a DialogFragment. This exception is throwing me:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

I have the "1.1.4-2" version of Kotlin In the import I have my layout:

import kotlinx.android.synthetic.main.layout_dialog_scan.*

and in the onCreateView method:

val viewRoot = inflater!!.inflate(R.layout.layout_dialog_scan, container, false)

img_close.setOnClickListener{ hideViews() }     
edit_code.addTextChangedListener(this)
//.....Más widgets

return viewRoot

This error disappears if I perform the bind based on the view:

val imageView = viewRoot.findViewById<ImageView>(R.id.img_close)
imageView.setOnClickListener{ hideViews() }   

Does anyone know the possible cause of the error?

    
asked by dámazo 08.10.2017 в 20:24
source

2 answers

0

The error turned out to be something simple and obvious. When invoking an element with this extension, internally perform a search:

getview().findViewById(R.id.nombre)

My mistake was to paint it in the onCreateView () method, at this stage the view is not yet created, the simple solution is to use the invocation of these widgets in the onViewCreated () method.

Along with that I found something interesting, to use it in a ViewHolder class of an adapter, extend it from LayoutContainer: information in English

    
answered by 09.10.2017 / 05:14
source
1

The error states that you can not call the setOnClickListener method in an ImageView instance with null value:

  

java.lang.NullPointerException: Attempt to invoke virtual method 'void   android.widget.ImageView.setOnClickListener (android.view.View $ OnClickListener) '   on a null object reference

You can not call a method of an instance with a null value of a view without first obtaining its reference by:

val imageView = viewRoot.findViewById<ImageView>(R.id.img_close)
imageView.setOnClickListener{ hideViews() }   

Obtaining these references and changing their properties can be done within the onCreate() method:

    
answered by 10.10.2017 в 01:17