繁体   English   中英

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

[英]Override toString() method of final BluetoothDevice class

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

据我所知,适配器在每个对象上调用toString方法。 但是,如果您在BluetoothDevice调用toString ,则BluetoothDevice返回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

一旦有了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()方法获取名称。 这样解决您的问题吗?

正如我在评论中已经提到的那样,您可以扩展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;
 }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM