Android自定义视图:如何在单个小部件上设置click listener
这是自定义视图的布局文件Android自定义视图:如何在单个小部件上设置click listener,android,xml,user-interface,custom-view,Android,Xml,User Interface,Custom View,这是自定义视图的布局文件 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation=
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="?actionBarSize">
<ImageView
android:id="@+id/ivMenu"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:background="@drawable/ripple"
android:clickable="true"
android:padding="12dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_menu_gray" />
<ImageView
android:id="@+id/ivDrawer"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:background="@drawable/ripple"
android:clickable="true"
android:padding="12dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_drawer_gray" />
</android.support.constraint.ConstraintLayout>
</LinearLayout>
放
fun setMenuListener(监听器:View.OnClickListener){
findviewbyd(R.id.ivMenu).setOnClickListener(listener)
}
有趣的setDrawerListener(监听器:View.OnClickListener){
findViewById(R.id.ivDrawer).setOnClickListener(listener)
}
进入自定义视图类。您可以使用ID访问
图像视图。您需要将膨胀视图添加到根(WolfBottomAppBar
);e、 g.在init方法中:
private fun init(context: Context) {
((context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)) as LayoutInflater).inflate(R.layout.wolf_bottom_app_bar, this, true)
ivMenu.setOnClickListener { Log.d(TAG, "Image ivMenu clicked!") }
}
不要忘记为布局文件导入合成Kotlin包,并将android:focusable=“true”
添加到两个ImageViewsXMLfun-setMenuListener(listener:View.OnClickListener){findViewById(R.id.ivMenu).setOnClickListener(listener)}fun-setDrawerListener(listener:View.OnClickListener){findviewbyd(R.id.ivDrawer).setOnClickListener(listener)}这有助于:)
fun setMenuListener(listener : View.OnClickListener) {
findViewById<ImageView>(R.id.ivMenu).setOnClickListener(listener)
}
fun setDrawerListener(listener : View.OnClickListener) {
findViewById<ImageView>(R.id.ivDrawer).setOnClickListener(listener)
}
private fun init(context: Context) {
((context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)) as LayoutInflater).inflate(R.layout.wolf_bottom_app_bar, this, true)
ivMenu.setOnClickListener { Log.d(TAG, "Image ivMenu clicked!") }
}