gpt4 book ai didi

java - 覆盖最终 BluetoothDevice 类的 toString() 方法

转载 作者:行者123 更新时间:2023-11-29 06:58:17 25 4
gpt4 key购买 nike

在我的 Android 应用程序中,我有一个 ListActivity显示蓝牙设备。我有一个 ArrayList<BluetoothDevice>ArrayAdapter<BluetoothDevice> .一切正常,但有一个问题。每个BluetoothDevice在列表中显示为 MAC 地址,但我需要显示其名称。

据我所知,适配器调用 toString每个对象的方法。但是BluetoothDevice如果您调用 toString 返回 MAC 地址在上面。所以解决方案是覆盖 toString并返回名称而不是地址。但是BluetoothDevice是最后一个类,所以我无法覆盖它!

关于如何强制蓝牙设备返回其名称而不是地址的任何想法? toString

最佳答案

你可以使用组合而不是继承:

 public static class MyBluetoothDevice {
BluetoothDevice mDevice;
public MyBluetoothDevice(BluetoothDevice device) {
mDevice = device;
}

public String toString() {
if (mDevice != null) {
return mDevice.getName();
}
// fallback name
return "";
}
}

当然,您的 ArrayAdapter 将使用 MyBluetoothDevice 而不是 BluetoothDevice

关于java - 覆盖最终 BluetoothDevice 类的 toString() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30184669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com