我可以给约束布局一个"hidden"变量吗?



我使用的是Kotlin、XML和android studio。

我有一个ConstraintLayout;按钮";。用户会点击它,它会把他们带到其他地方。它们是程序生成到回收视图中的,因此我无法将数据硬核到它们中。关于他们的创作,有没有一种方法可以给他们一个";隐藏的";单击它们时可以引用的变量。如果我使用一个按钮,我只需要将文本设置为这个值,然后引用它的文本。

您可以为布局分配一个id,您可以将该id用作查找该视图的引用。

以下是一些示例代码


class MyAdapter():RecyclerView.Adapter<VH>() {
override fun onCreateView()
override fun onBindView(holder:VH, position:Int):VH {
holder.layout.setOnClickListener {
//do something when view is clicked
}
}

class VH(view:View):RecyclerView.ViewHolder(view) {
//here you can get a reference to your layout
val layout = view.findViewById<ConstraintLayout>(R.id.someId)
}
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
andoid:id="@+id/someId" <----- This is the important bit here
android:backgroundTint="@android:color/white"
android:layout_height="wrap_content">
<TextView
android:id="@+id/header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:textColor="@color/primaryText"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Header" />

您可以在生成布局时使用View.setId()-甚至还有一个方便的generateViewId()函数可以为您生成一个,它保证不会与您在R文件中定义的任何ID冲突

但是,View.OnClickListener中的onClick方法也会传入作为参数单击的视图,所以您可能不需要查找任何内容?如果您使用lambda,它会隐式传递为it(因为它是一个单独的参数(,所以您可能没有意识到它在那里,但您可以显式地将其命名为view或任何

layout.setOnClickListener { view -> ... }

但如果都是程序性的,也许只需要使用一个函数?

fun onLayoutClick(layout: View) { ... }
...
layout.setOnClickListener(::onLayoutClick)

该函数具有与lambda相同的签名(相同的参数和返回类型(,因此您可以像一样插入函数引用

相关内容

最新更新