我最近切换到kotlin,创建了一个活动并在其中添加了很少的视图,但是我的TextView
上的点击侦听器无法正常工作。
以下是我的xml文件。
<TextView
android:id="@+id/tvHomeSignIn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:background="@drawable/signin_curve_allside"
android:paddingLeft="8dp"
android:paddingTop="4dp"
android:paddingRight="8dp"
android:paddingBottom="4dp"
android:text="SIGN IN"
android:textAllCaps="true"
android:textColor="@color/white"
android:textSize="12dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="@+id/imageView21"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="@+id/imageView21"
app:layout_constraintVertical_bias="0.173" />
MainActivity.kt
class HomeActivityV2 : AppCompatActivity{
lateinit var tvSignIn: TextView
lateinit var ivHomeTeam:ImageView
lateinit var ivAwayTeam:ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home_v2)
tvSignIn= findViewById(R.id.tvHomeSignIn)
tvSignIn.setOnClickListener(clickListener)
}
val clickListener = View.OnClickListener {view ->
when (view.getId()) {
R.id.tvHomeSignIn -> launchSignInActivity()
}
}
}
答案 0 :(得分:1)
将扩展插件添加到build.gradle文件中,这样就不再需要使用findViewById。
apply plugin: 'kotlin-android-extensions'
然后,您应该可以像这样添加点击侦听器:
tvSignIn.setOnClickListener { view ->
launchSignInActivity()
}
答案 1 :(得分:0)
您只需要执行以下操作->
class HomeActivityV2 : AppCompatActivity(), View.OnClickListener{
lateinit var tvSignIn: TextView
lateinit var ivHomeTeam:ImageView
lateinit var ivAwayTeam:ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home_v2)
tvSignIn= findViewById(R.id.tvHomeSignIn)
tvSignIn.setOnClickListener(clickListener)
}
override fun onClick(view: View) {
when (view.id) {
R.id.tvHomeSignIn ->launchSignInActivity()
}
}
private fun launchSignInActivity(){
///Your intent method over here.
}
}
它与Java相同,但有些不同。检查一下,让我知道。谢谢。