Displaying custom objects in ArrayAdapter - the easy way?

android, android-arrayadapter

Solution

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.

Problem

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(); } ... } ```

Original source