问题
I bet it's a trivial mistake. But here I sit, wasting hours on it:
I have a simple app that scans for Bluetooth devices and shows the discovered devices' information in cards in a RecyclerView (one card per device). Clicking on one of the CardViews initiates the connection to the respective device.
That works fine after the scan has stopped (after some seconds) and the cards aren't bound to new data anymore. During the scan however, only few of the touches onto the cards are recognized.
I'm setting the click listener in onCreateViewHolder()
like this:
@Override
public DeviceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
CardView cardView = (CardView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view, parent, false);
cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick() called with: v = [" + v + "]");
}
});
return new DeviceViewHolder(cardView);
}
My first guess was that the CPU was loaded to full because each Bluetooth device discovery is handled on the main thread (I think). But the profiler shows that the CPU is only loaded to 15%.
This is my callback that is executed on device discovery (which happens a few dozen times per second):
bluetoothAdapter.startLeScan(callback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
// update List<BluetoothDevice> that is shown by the RecyclerView.Adapter
devicesAdapter.notifyDataSetChanged();
}
});
I'm not sure whether it has something to do with my Bluetooth callback being called rapidly or if it's because my ViewHolders are bound to new data rapidly during the scan.
回答1:
Instead you can place the setOnClickListener
inside your class that extends RecyclerView.ViewHolder
.
class MyViewHolder extends RecyclerView.ViewHolder {
TextView txtDate;
TextView txtDescription;
MyViewHolder (View itemView) {
super(itemView);
//...findViewById
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = getAdapterPosition();
//Do something here...
}
});
}
So your onCreateViewHolder(...)
method becomes:
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.my_layout, parent, false);
return new MyViewHolder(view);
}
来源:https://stackoverflow.com/questions/49101115/recyclerview-item-onclick-not-working-while-being-updated-rapidly