【发布时间】:2017-04-18 16:16:26
【问题描述】:
作为一名 Android 开发人员,我开始了解 Kotlin。做android应用的时候,习惯用Databinding、retrolambda等,现在在Kotlin中如何解决下面的情况有点迷茫。
我通常如何在 java 中做到这一点
我有一个Adapter(扩展RecyclerView.Adapter),用于显示BluetoothDevices 列表的RecyclerView。通常,我所有的项目都有一个通用接口 TypedClickListener,它将返回用户单击的列表项的 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>
现在,把所有东西放在一起:
在 Activity 中将 TypedClickListener 传递给 Adapter:
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 函数。
【问题讨论】:
标签: android kotlin android-databinding