在a simple app project at GitHub中,我只有2个自定义Java文件:
Adapter
和ViewHolder
,用于在RecyclerView
中显示蓝牙设备当用户点击
RecyclerView
中的蓝牙设备时,MainActivity.java包含要调用的方法:public void confirmConnection(String address) {
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to pair to " + device + "?");
builder.setPositiveButton(R.string.button_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
device.createBond();
}
});
builder.setNegativeButton(R.string.button_cancel, null);
builder.show();
}
在
ViewHolder
类(在DeviceListAdapter.java中)中,定义了单击监听器:public class DeviceListAdapter extends
RecyclerView.Adapter<DeviceListAdapter.ViewHolder> {
private ArrayList<BluetoothDevice> mDevices = new ArrayList<BluetoothDevice>();
protected static class ViewHolder
extends RecyclerView.ViewHolder
implements View.OnClickListener {
private TextView deviceAddress;
public ViewHolder(View v) {
super(v);
v.setOnClickListener(this);
}
@Override
public void onClick(View v) {
String address = deviceAddress.getText().toString();
Toast.makeText(v.getContext(),
"How to call MainActivity.confirmConnection(address)?",
Toast.LENGTH_SHORT).show();
}
}
我的问题:
如何从
confirmConnection(address)
的ViewHolder
方法调用onClick
方法?我一直在2个Java文件之间移动
ViewHolder
类声明,还尝试将其放入自己的文件中-只是找不到正确的方法。我是否应该在
ViewHolder
类中添加一个字段,并在何时存储对MainActivity
实例的引用?更新:
这对我有用,但似乎是一种解决方法(而且我还在考虑使用
LocalBroadcastReceiver
-这将是一个更加棘手的解决方法)- @Override
public void onClick(View v) {
String address = deviceAddress.getText().toString();
try {
((MainActivity) v.getContext()).confirmConnection(address);
} catch (Exception e) {
// ignore
}
}
最佳答案
为了使您的类保持解耦,建议您在适配器上定义一个接口(interface),例如:
public interface OnBluetoothDeviceClickedListener {
void onBluetoothDeviceClicked(String deviceAddress);
}
然后在适配器中为此添加一个setter:
private OnBluetoothDeviceClickedListener mBluetoothClickListener;
public void setOnBluetoothDeviceClickedListener(OnBluetoothDeviceClickedListener l) {
mBluetoothClickListener = l;
}
然后在内部,在您的
ViewHolder
的onClick()
中:if (mBluetoothClickListener != null) {
final String addresss = deviceAddress.getText().toString();
mBluetoothClickListener.onBluetoothDeviceClicked(address);
}
然后将
MainActivity
传递给Adapter
的监听器:mDeviceListAdapter.setOnBluetoothDeviceClickedListener(new OnBluetoothDeviceClickedListener() {
@Override
public void onBluetoothDeviceClicked(String deviceAddress) {
confirmConnection(deviceAddress);
}
});
这样,您以后就可以重新使用适配器,而不必将其与特定行为联系在一起。
关于android - 如何从RecyclerView.Adapter中的ViewHolder调用MainActivity方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32720702/