我制作了自定义 ListView 和 ListView 适配器。不知何故,相同的数据在我的 ListView 中显示多次,但我不知道为什么。
我尝试调试一下,但好像没有双重添加。
如您所见,我通过使用 .contains 控制适配器的输入,但这没有帮助。
广播接收器
private BroadcastReceiver BR_BT_Device= new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action_BR_BT_Device= intent.getAction();
if(action_BR_BT_Device.equals(BluetoothDevice.ACTION_FOUND))
{
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (!device.equals(null)) {
String sDevice_Address = device.getAddress();
if (!(sDevice_Address == null)) {
if (device.getName() == null){
mDeviceName = "Kein Name";
}
else {
mDeviceName = device.getName();
}
cBT_DeviceList mDevice = new
cBT_DeviceList(mDeviceName, sDevice_Address);
if (!(cBT_popup.mBTDevice.contains(mDevice))) {
cBT_popup.mBTDevice.add(mDevice);
cBT_popup.cBTDeviceListAdapter.notifyDataSetChanged();
}
}
}
Log.d("Resiver", "onReceive: "+device.getAddress());
}
}
};
ListView 对象的 Activity
public class cBT_popup extends MainActivity {
public static ArrayList<cBT_DeviceList> mBTDevice = new
ArrayList<cBT_DeviceList>();
public ListView lv_devices;
public static cBT_DeviceList_Adapter cBTDeviceListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bt_popup);
lv_devices = findViewById(R.id.lv_devices);
cBTDeviceListAdapter = new cBT_DeviceList_Adapter(this,
R.layout.lrv_bt_listview, mBTDevice);
lv_devices.setAdapter(cBTDeviceListAdapter);
lv_devices.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
如果您需要更多信息,请告诉我。
如果这很重要:突出显示所选项目是不可能的,目前不知道为什么。
用于广播的 IntentFilter
´´´
IntentFilter BT_Device_filter = 新
IntentFilter(BluetoothDevice.ACTION_FOUND);
´´´
最佳答案
可能同一蓝牙设备多次调用 onRecieve。
试试这个...替换
if (!(cBT_popup.mBTDevice.contains(mDevice))) {
cBT_popup.mBTDevice.add(mDevice);
cBT_popup.cBTDeviceListAdapter.notifyDataSetChanged();
}
与
boolean alreadyExist = false;
for(cBT_DeviceList mBTDeviceObj : mBTDevice){
if(mDevice.getName().equals(mBTDeviceObj.getName())){
alreadyExist = true;
}
}
if (!alreadyExist) {
cBT_popup.mBTDevice.add(mDevice);
cBT_popup.cBTDeviceListAdapter.notifyDataSetChanged();
}
关于java - 相同的适配器对象显示多次,但为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56359822/