在ArrayAdapter中显示自定义对象-简单的方法? [英] Displaying custom objects in ArrayAdapter - the easy way?

查看:214
本文介绍了在ArrayAdapter中显示自定义对象-简单的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在ArrayAdapter中显示蓝牙设备的列表,并且想要覆盖适配器的默认功能以显示对象toString().我知道有些解决方案可以扩展getView(...)方法,但是我真的觉得这太过复杂了.我要覆盖的是如何构建要显示的字符串.对于蓝牙设备,这将使用getName()而不是toString().

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().

因此,我创建了一个如下所示的自定义arrayadapter,并且理想情况下将具有类似于getDisplayString(T value)

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

推荐答案

更改getView的行为不必那么复杂.

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

这具有以下缺点:将视图的文本设置为两次以上(在super.getView中一次,在覆盖中一次),但是花费不多.另一种方法是,如果convertView不存在,请使用充气机自己创建视图.

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.

这篇关于在ArrayAdapter中显示自定义对象-简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆