【问题标题】:Override toString() method of final BluetoothDevice class覆盖最终 BluetoothDevice 类的 toString() 方法
【发布时间】:2015-05-12 07:41:10
【问题描述】:

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

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

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

【问题讨论】:

  • 扩展 ArrayAdapter 并使用适配器内部的其他方法而不是 toString
  • 我认为这是最好的解决方案。谢谢!
  • 感谢您的回复 - 我添加了我的评论作为答案

标签: java android overriding android-arrayadapter tostring


【解决方案1】:

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

 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

【讨论】:

  • 是的,这可能是解决方案。但是我正在使用 BluetoothDevice 中的许多方法和字段,因此我将在 MyBluetoothDevice 类中实现所有这些方法...
  • 你可以有一个 getter 来返回 BluetoothDevice 对象
【解决方案2】:

一旦你有了你的 ArrayList

ArrayList<BluetoothDevice> btDeviceArray = new ArrayList<BluetoothDevice>();
ArrayAdapter<String> mArrayAdapter;

现在您可以在 onCreateView 中添加设备,例如:

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_1);
        setListAdapter(mArrayAdapter);

Set<BluetoothDevice> pariedDevices = mBluetoothAdapter.getBondedDevices();
        if(pariedDevices.size() > 0){
            for(BluetoothDevice device : pariedDevices){
                mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                btDeviceArray.add(device);
            }
        }

所以请注意,您可以使用.getName() 方法获取名称。这解决了你的问题?

【讨论】:

  • 但是 ArrayList 和 ArrayAdapter 必须包含相同类型的对象。在您的提案中,ArrayList 包含 BluetoothDevice 对象,而 ArrayAdapter 包含 String 对象。这会引发错误...
【解决方案3】:

正如我在评论中已经提到的,您可以扩展 ArrayAdapter 和 使用其他方法而不是 toString 方法。

例如:

public class YourAdapter extends ArrayAdapter<BluetoothDevice> {
   ArrayList<BluetoothDevice> devices;
   //other stuff
 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
   //get view and the textView to show the name of the device
   textView.setText(devices.get(position).getName());
   return view;
 }
}

【讨论】:

    猜你喜欢
    • 2012-01-11
    • 2018-01-10
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    相关资源
    最近更新 更多