xml onClick中的Kotlin无法正常工作 [英] Kotlin in xml onClick not work
问题描述
我正在学习科特林,现在对我来说一点也不困难.我有xml
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" />
和片段
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:
在父级或祖先中找不到方法clickItemHoro(View) 在视图类上定义的android:onClick属性的上下文 id为"aries"的android.support.v7.widget.AppCompatImageView
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
推荐答案
如上所述,添加Kotlin扩展名是一个好主意,此外,您可以直接在代码中的ImageView
上设置onClickListener而不用声明方法在您的xml文件中:onClick
:
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() }
这篇关于xml onClick中的Kotlin无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!