How to call a MainActivity method from ViewHolder in RecyclerView.Adapter?

前端 未结 5 1155
眼角桃花
眼角桃花 2020-12-09 05:45

In a simple app project at GitHub I have only 2 custom Java-files:

  1. MainActivity.java contains Bluetooth- and UI-related source code
  2. DeviceListAdapter.
5条回答
  •  时光说笑
    2020-12-09 06:01

    To keep your classes decoupled, I'd suggest defining an interface on your adapter, something like:

    public interface OnBluetoothDeviceClickedListener {
        void onBluetoothDeviceClicked(String deviceAddress);
    }
    

    Then add a setter for this in your adapter:

    private OnBluetoothDeviceClickedListener mBluetoothClickListener;
    
    public void setOnBluetoothDeviceClickedListener(OnBluetoothDeviceClickedListener l) {
        mBluetoothClickListener = l;
    }
    

    Then internally, in your ViewHolder's onClick():

    if (mBluetoothClickListener != null) {
        final String addresss = deviceAddress.getText().toString();
        mBluetoothClickListener.onBluetoothDeviceClicked(address);
    }
    

    Then just have your MainActivity pass in a listener to the Adapter:

    mDeviceListAdapter.setOnBluetoothDeviceClickedListener(new OnBluetoothDeviceClickedListener() {
        @Override
        public void onBluetoothDeviceClicked(String deviceAddress) {
            confirmConnection(deviceAddress);
        }
    });
    

    This way you can reuse the adapter later without it being tied to that particular behavior.

提交回复
热议问题