In a simple application project on GitHub , I have only 2 custom Java files:

MainActivity.java contains a method that will be called when a user clicks on a Bluetooth device in RecyclerView :
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(); }
And in the ViewHolder class (in DeviceListAdapter.java ) the receiver of clicks is defined:
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(); } }
My problem:
How to call confirmConnection(address) method from ViewHolder onClick method?
I keep moving the ViewHolder class ViewHolder between the two Java files, and also try to put it in my own file - and just can't find the right path.
Should I add a field to the ViewHolder class and (when?) Store a reference to the MainActivity instance?
UPDATE:
This works for me, but it seems to be a workaround (and also I was thinking of using LocalBroadcastReceiver - which would be an even more hacker workaround) -
@Override public void onClick(View v) { String address = deviceAddress.getText().toString(); try { ((MainActivity) v.getContext()).confirmConnection(address); } catch (Exception e) {
android android-recyclerview android-viewholder android-bluetooth
Alexander farber
source share