2013-07-23 54 views
1

我试图在ArrayAdapter中显示蓝牙设备列表,并且想要覆盖适配器的默认功能以显示对象toString()。我知道有些解决方案可以扩展getView(...)方法,但我真的觉得这是过度复杂的事情。我只想要重写如何构建显示的字符串。对于蓝牙设备,这将使用getName()而不是toString()在ArrayAdapter中显示自定义对象 - 简单的方法?

所以我创建了一个自定义的arrayadapter像的下方,并且在理想情况下有东西像getDisplayString(T value)

public class MyArrayAdapter extends ArrayAdapter<BluetoothDevice> { 
    ... 
    @Override //I wish something like this existed 
    protected String getDisplayString(BluetoothDevice b) { 
     return b.getName(); 
    } 
    ... 
} 

回答

3

尝试是这样的一种方法:(注:我还没有尝试)

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

} 
+0

通过这样做,我不能使用arrayAdapter作为蓝牙设备的容器... –

4

改变getView的行为不一定非常复杂。

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; 
    } 
}; 

这样做(在覆盖在super.getView各一次)两次以上设置视图的文本的缺点,但这并不值多少钱。另一种方法是在convertView不存在的情况下使用充气器自己创建视图。

+1

经过多次寻找,我找到了最简单的解决方案,它的工作原理非常完美!话虽如此,是否有理由为什么ListView不会简单地让您设置显示字段名称?我不知道 – peterb

+0

可能是因为他们真的希望你提供一个自定义的.toString()行为的对象。在这里,你可以用你自己的类包装BluetoothDevice,并使toString做你想做的任何事情。我同意你的OP,但是有一个可重写的getDisplayString方法会更容易。 – gladed

相关问题