[英]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.