3

I am trying to display a list of Bluetooth devices in an ArrayAdapter, and want to override the default functionality of the adapter to show the objects toString(). I know that there are solutions that extend the getView(...) method, but I really feel this is over-complicating things. All I want is to override how the string to display is built. For Bluetooth devices this would be using getName() instead of toString().

So I've created a custom arrayadapter like below, and would ideally have a method that is something like the getDisplayString(T value)

public class MyArrayAdapter extends ArrayAdapter<BluetoothDevice> {
    ...
    @Override //I wish something like this existed
    protected String getDisplayString(BluetoothDevice b) {
        return b.getName();
    }
    ...
}
Runar Halse
  • 3,528
  • 10
  • 39
  • 59

2 Answers2

10

Altering the behavior of getView doesn't have to be that complicated.

mAdapter = new ArrayAdapter<MyType>(this, R.layout.listitem, new ArrayList<MyType>()) {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView view = (TextView) super.getView(position, convertView, parent);
        // Replace text with my own
        view.setText(getItem(position).getName());
        return view;
    }
};

This has the disadvantage of setting the view's text twice (once in super.getView and once in the override) above, but that doesn't cost much. The alternative is to create the view yourself using an inflater if convertView isn't there.

gladed
  • 1,705
  • 1
  • 17
  • 25
  • 1
    After much hunting around, simplest solution that I found and it works perfect! Having said that, is there are reason why the ListView doesn't simply allow you to set the display field name? I wonder – peterb Apr 17 '16 at 10:55
  • Probably because they really want you to supply an object with customized .toString() behavior. Here, you could wrap BluetoothDevice with your own class and make toString do whatever you want. I agree with your OP though, it would be easier to have an overridable getDisplayString method. – gladed Apr 18 '16 at 19:55
3

Try something like this: (Note: that I havent try it. )

public class MyArrayAdapter extends ArrayAdapter<Object> {
  public MyArrayAdapter(Context c, List<Object> data){
   super(c, 0, data);
   mData = data;

 }
 @Override
 public Object getItem(int position){
    return ((BluetoothDevice)mData.get(position)).getName();
  }

}
Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148