2015-05-12 118 views
1

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

因为我知道每个对象的适配器调用toString方法。但是BluetoothDevice返回MAC地址,如果你打电话给toString。所以解决方法是重写toString并返回名称而不是地址。但BluetoothDevice是最后一堂课,所以我无法覆盖它!

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

+1

扩展ArrayAdapter并使用其他方法适配器代替的toString – Zelldon

+0

里面我觉得这是最好的解决办法。谢谢! – DanielH

+0

thx为响应 - 我添加了我的评论作为回答 – Zelldon

回答

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; 
} 
} 
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()方法得到的名称。这解决了你的问题?

+0

但ArrayList和ArrayAdapter必须包含相同类型的对象。在您的建议中,ArrayList包含BluetoothDevice对象,而ArrayAdapter包含String对象。这会引发错误... – DanielH

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

+0

是的,这可能是解决方案。但是我使用BluetoothDevice的很多方法和领域,所以我将在MyBluetoothDevice类中实现所有这些方法... – DanielH

+1

您可以使用返回BluetoothDevice对象的getter – Blackbelt