Android Studio BLE开发:添加LeDeviceListAdapter解决未解析引用报错
问题根因
LeDeviceListAdapter不属于Android SDK内置公开类,不存在API版本适配导致找不到的问题。该类是Android官方BLE demo中自定义的列表适配器实现,你当前代码直接调用了这个类但没有在项目中定义对应实现,是触发Unresolved Reference: LeDeviceListAdapter报错的唯一原因。
之前复制第三方源码导入失败,基本都是类存放路径错误、包名不匹配、类名拼写不一致导致的。
正确接入步骤
- 新建类文件
打开项目导航栏中java/[你的项目应用包名]目录(和你写当前Fragment/Activity代码的目录同级),新建Kotlin类,类名必须严格为LeDeviceListAdapter,大小写完全匹配。 - 补全类实现
将下述代码粘贴到新建的类文件中,注意将文件顶部的包名替换为你项目实际的包名:
// 替换为你自己项目的包名,例如 package com.example.blebeaconapp import android.bluetooth.BluetoothDevice import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView import java.util.ArrayList class LeDeviceListAdapter : BaseAdapter() { private val leDevices: MutableList<BluetoothDevice> = ArrayList() // 对应你代码中调用的addDevice方法,自带设备去重逻辑 fun addDevice(device: BluetoothDevice) { for (existingDevice in leDevices) { if (existingDevice.address == device.address) return } leDevices.add(device) } // 清空列表方法,重新扫描时调用 fun clear() { leDevices.clear() } override fun getCount(): Int = leDevices.size override fun getItem(position: Int): Any = leDevices[position] override fun getItemId(position: Int): Long = position.toLong() override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val itemView = convertView ?: LayoutInflater.from(parent?.context) .inflate(android.R.layout.simple_list_item_2, parent, false) val device = leDevices[position] itemView.findViewById<TextView>(android.R.id.text1).text = device.name ?: "未知BLE设备" itemView.findViewById<TextView>(android.R.id.text2).text = device.address return itemView } }
- 修正现有代码的逻辑遗漏
你贴的代码还有几处会导致功能跑不通的问题,一并修正:- 蓝牙不支持的提示Toast只创建未调用
show()方法,不会弹出提示,修改为Toast.makeText(context, text, duration).show() - 定义完
scanLeDevice()方法后没有主动调用,点击按钮不会触发扫描,需要在方法定义后加一行scanLeDevice() - 初始化完适配器没有绑定到列表控件:需要先在对应布局文件中添加一个
ListView(示例用id为lv_ble_devices),在适配器初始化代码后添加绑定逻辑:
val deviceListView = view.findViewById<ListView>(R.id.lv_ble_devices) deviceListView.adapter = leDeviceListAdapter- Android 12及以上版本需要在代码中动态申请
BLUETOOTH_SCAN、BLUETOOTH_CONNECT运行时权限,否则扫描操作会被系统拦截无结果。
- 蓝牙不支持的提示Toast只创建未调用
额外说明
- 每次重新开始扫描前,可以调用
leDeviceListAdapter.clear()清空旧的设备列表,避免残留上次扫描的结果。 - 如果你后续要改用
RecyclerView实现列表,只需要把LeDeviceListAdapter的继承类从BaseAdapter换成RecyclerView.Adapter对应实现即可,核心的设备存储、去重逻辑不需要改。
内容的提问来源于stack exchange,提问作者gpeck
相关产品推荐
相关产品推荐

