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

时间:2015-05-12 07:41:11

标签: java android override android-arrayadapter tostring

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

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

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

3 个答案:

答案 0 :(得分:3)

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

 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

答案 1 :(得分: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()方法获取名称。这可以解决你的问题吗?

答案 2 :(得分:1)

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