替换Kotlin中的java通用接口进行数据绑定
我开始认识Kotlin作为Android开发人员。 在制作android应用程序时,我习惯于使用Databinding,retrolambda等等。现在我在如何解决Kotlin中的以下情况方面有些迷茫。
我通常会这样做在java中
我有一个Adapter
(扩展RecyclerView.Adapter
)的RecyclerView
显示BluetoothDevice
列表。 通常,我所有的项目都有一个通用接口TypedClickListener,它将返回用户点击的listitem的T对象。 像这样:
通用接口:
public interface TypedClickListener<T> { void onClick(T t); }
PairedDeviceAdapter的构造函数
public PairedDeviceAdapter(Context context, BluetoothDevice[] devices, TypedClickHandler<BluetoothDevice> handler){ mContext = context; mDevices = devices mClickHandler = handler; }
适配器的onBindViewHolder :(持有者包含数据绑定布局)
public void onBindViewHolder(DatabindViewHolder holder, Int position) { holder.getBinding().setVariable(BR.device, mDevices[position]); holder.getBinding().setVariable(BR.handler, mClickHandler); }
布局本身:
<layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <import type="android.bluetooth.BluetoothDevice"/> <import type="com.example.TypedClickHandler"/> <variable name="device" type="BluetoothDevice"/> <variable name="handler" type="TypedClickHandler"/> </data> <LinearLayout ... // width, height, etc android:onClick="@{v->handler.onClick(device)}"> ... // Row layout etc </LinearLayout> </layout>
现在把所有东西放在一起:
将TypedClickListener传递给活动中的适配器:
mAdapter = PairedDeviceAdapter(this, devices, (bluetoothDevice) -> { // The code that is ran when user clicks a device }
我是如何在Kotlin中做到这一点的
如上所述,我正在努力用Kotlin来做到这一点。 看来我可以跳过一个TypedClickListener
的步骤,因为我可以使用一个简单的内联函数(BluetoothDevice) -> Unit
。
PairedDeviceAdapter看起来像这样:
class PairedDeviceAdapter(val context: Context, val clickHandler : (BluetoothDevice) -> Unit ) : RecyclerView.Adapter<DatabindViewHolder>() {
onBindViewHolder看起来有点像它的Java版本。 但是,我不知道如何将我的布局绑定到clickhandler,因为我没有clickhandler的类型。
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <import type="android.bluetooth.BluetoothDevice"/> <import type="???"/> <variable name="device" type="BluetoothDevice"/> <variable name="handler" type="???"/> </data> <LinearLayout ... android:onClick="@{v->handler.???(device)}"> ... // close everything
题
如何在Kotlin中创建相同的结构,或者是否有其他(更智能的)解决方案来将适配器 – 行单击绑定到Activity
(或Fragment
)中定义的lambda函数。
你可以在你的类中有一个方法,例如onSomeClick()
,并且像这样调用它: android:onClick="@{onSomeClick}"