Kotlin in xml onClick not work

孤者浪人 提交于 2021-01-27 05:59:36

问题


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


回答1:


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.*



回答2:


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




回答3:


As mentioned above it's a good idea to add the Kotlin extensions, additionally you could set an onClickListener on the ImageView directly in your code instead of declaring the method in your xml files: onClick:

aries.setOnClickListener { doSomething() }




回答4:


In Gradle file add

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

then activity add

   import kotlinx.android.synthetic.main.activity_main.*



回答5:


Based on the above answers and comments posting the full solution here so that it would be helpful for others.

First remove android:onClick attribute from the xml code of ImageView.

Then change the fragment code as below:

class ChooseYourHoroscope : Fragment(){
  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
      val view = inflater.inflate(R.layout.fragment_welcome_old, container, false)
      val aries = view.findViewById<ImageView>(R.id.aries)
      aries.setOnClickListener{
          //Write ur action here
      }

      return view;
   }
}


来源:https://stackoverflow.com/questions/40885426/kotlin-in-xml-onclick-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!