Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin in xml onClick not work

I learning kotlin, and now for me not cearly some moment. I have xml

<ImageView
                    android:id="@+id/aries"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="10dp"
                    android:tag="1"
                    android:onClick="clickItemHoro"
                    android:src="@drawable/aries" />

and fragment

class ChooseYourHoroscope : Fragment(){

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_welcome_old, container, false)

        return view;
    }

    fun clickItemHoro(v: View?){
        Log.e("clickItemHoro", v!!.tag.toString())
    }

}

when i click button i have error:

Could not find method clickItemHoro(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageView with id 'aries'

why it happen? Code vary simple, but it not work, i cant understand why

like image 401
g71132 Avatar asked Oct 18 '22 21:10

g71132


2 Answers

Try to use Kotlin Extensions plugin, it should work.

in build.gradle (app) add apply plugin: 'kotlin-android-extensions'

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

then import it in MainActivity.kt

import kotlinx.android.synthetic.main.activity_main.*
like image 94
Dian Avatar answered Oct 21 '22 07:10

Dian


apply plugin: 'kotlin-android-extensions' must use kotlin extenstion Then it will work

like image 28
Tarun konda Avatar answered Oct 21 '22 08:10

Tarun konda