android开发中替换SimpleAdapter提高代码质量 [英] Replace SimpleAdapter in android development to improve code quality
问题描述
目前,我使用 HashMap
和 SimpleAdapter
对象在我的 ListView
中显示用户数据,但是现在我想用包含真实用户对象的 ArrayList
替换 HashMap
.
At the moment, I use a HashMap<String, String>
and a SimpleAdapter
object to display user data in my ListView
, but now I want to replace the HashMap<String, String>
with an ArrayList<User>();
containing real user objects.
这是我的代码:
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 });
如何用ArrayList
替换HashMap
?是否有专门用于此目的的类?
How is it possible to replace the HashMap
with the ArrayList
? Is there a specific class for this purpose?
任何帮助将不胜感激.
推荐答案
最简单的方法是在 User 类中覆盖 toString
以返回要显示的信息,并使用ArrayAdapter<用户>
.或者你可以拥有你的 CustomAdapter
,它扩展了 BaseAdapter
并实现了它的抽象方法.特别是您有 getCount
方法,它返回数据集包含的元素数,getItem(int position)
返回数据集在位置的对象,getView(int, View, ViewGroup)
,您必须使用它来扩充和自定义您的视图
the easiest way would be to override toString
inside your User class in order to return the information you want to display, and use an ArrayAdapter<User>
. Or you can have your CustomAdapter
, which extends BaseAdapter
and implements its abstract method. In particulare you have the getCount
method, which returns the number of elements that your dataset holds, getItem(int position)
which returns the object of your dataset at position, and getView(int, View, ViewGroup)
, that you have to use to inflate and customize your view
这篇关于android开发中替换SimpleAdapter提高代码质量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!