【问题标题】:Replace SimpleAdapter in android development to improve code quality在android开发中替换SimpleAdapter提高代码质量
【发布时间】:2014-10-09 17:55:25
【问题描述】:

目前,我使用HashMap<String, String>SimpleAdapter 对象在ListView 中显示用户数据,但现在我想将HashMap<String, String> 替换为包含真实用户对象的ArrayList<User>();

这是我的代码:

HashMap<String, String> map = new HashMap<String, String>();

                map.put(TAG_USERNAME, c.getString(TAG_USERNAME));
                map.put(TAG_FIRSTNAME, c.getString(TAG_FIRSTNAME));
                map.put(TAG_LASTNAME, c.getString(TAG_LASTNAME));
                map.put(TAG_ADDRESS, c.getString(TAG_ADDRESS));
                usersList.add(map);

[...]

ListAdapter adapter = new SimpleAdapter(this, usersList,
                    R.layout.single_user, new String[] { TAG_USERNAME,
                            TAG_FIRSTNAME, TAG_LASTNAME, TAG_ADDRESS },
                    new int[] { R.id.textViewUsername, R.id.textViewFirstName,
                            R.id.textViewLastName, R.id.textViewAddress });

如何将HashMap 替换为ArrayList?是否有专门用于此目的的类?

任何帮助将不胜感激。

【问题讨论】:

    标签: java android arraylist


    【解决方案1】:

    最简单的方法是在您的 User 类中覆盖 toString 以返回您想要显示的信息,并使用 ArrayAdapter&lt;User&gt;。或者你可以拥有你的CustomAdapter,它扩展了BaseAdapter 并实现了它的抽象方法。特别是你有 getCount 方法,它返回你的数据集包含的元素的数量,getItem(int position) 它返回你的数据集在位置的对象,以及 getView(int, View, ViewGroup),你必须使用它来膨胀和自定义你的视图

    【讨论】:

    • 感谢您的帮助。使用ArrayAdapter&lt;User&gt; 时,我需要遍历我的ArrayList&lt;User&gt; 并始终调用user.toString() 以获取所有用户信息的数组,对吧?
    • 不,适配器会处理它
    • 好的,但是当我这样称呼它ListAdapter arrAdapter = new ArrayAdapter&lt;User&gt;(this, R.layout.single_user, usersArrList); 时,我得到java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView,因为我有多个TextView,我无法像SimpleAdapter 那样应用多个id 作为参数。跨度>
    • 那么你必须继承它。您还可以继承 ArrayAdaper 并仅覆盖 getview
    猜你喜欢
    • 2010-09-14
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    相关资源
    最近更新 更多