早上好
我似乎遗漏了一条信息(仍在学习我的第一个 Android 应用程序)将 ArrayAdapter 连接到 View 。我创建了一个我们称之为 MyInfoClass 的类,它只是一些用于保存数据的属性。我用数据行填充类,最后我有一个 ArrayList(MyInfoClass>. 到目前为止一切顺利,一切看起来都很棒,并且值与我在 Debug 透视图中所期望的一样。
我还有一个 XML 布局,上面有一些 TextView。我想使用此布局来显示 ArrayList(MyInfoClass> 中保存的不同“数据集”。我知道要做到这一点,我会使用 ArrayAdapter 并使用以下行:
ArrayAdapter<MyInfoClass> X = new ArrayAdapter<MyInfoClass>(this, R.layout.main, R.id.txtvw_PrevLift, ld_data);
(ld_data 是 ArrayList(MyInfoClass> 对象)
我的困惑来自于……嗯,来自于不知道我在做什么,但无论如何,它来自于不理解如何将 MyInfoClass 的属性连接到它们相应的 TextView。 ArrayAdapter 文档没有显示采用 TextView id 列表的构造函数????
谢谢您的帮助。 JB
为了帮助消除我的困惑,我没有绑定(bind)到列表....也许我应该?我只是想让整个 View 代表一行数据。为了可读性,我已经修剪了很多代码,但这是我的观点。一些 TextView 是静态标签,其他的会被填充。这些按钮用于来回导航。
<RelativeLayout....>
<ImageView
android:id=.../>
<TextView
android:id=.../>
<ImageView
android:id=.../>
<TextView
android:id=.../>
<TextView
android:id=.../>
<TextView
android:id=.../>
<Button
android:id=.../>
<Button
android:id=.../>
</RelativeLayout>
最佳答案
在你的情况下最好使用 SimpleAdapter
您定义一个 XML 文件来代表您的列表项。此 XML 文件将包含 TextViews
,您将在其中显示来自 MyInfoClass
的数据。假设它是 my_list_item.xml
<LinearLayout...>
<TextView android:id=name.../>
<TextView android:id=gender.../>
<TextView android:id=occupation.../>
</LinearLayout>
假设您将它们的数据作为 MyInfoClass.getName()、.getGender()、.getOccupation()
您创建一个 map 列表,每个 map 代表一个列表项的数据:
List<HashMap<String, String>> maps = new ArrayList<HashMap<String, String>>();
您用您的信息填写此列表:
for(int i=0; i<myArray.size(); ++i) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", myArray.get(i).getName());
map.put("gender", myArray.get(i).getGender());
map.put("occupation", myArray.get(i).getOcupation());
maps.add(map); // add this entry to the list
);
您还创建了 2 个数组:一个包含键的名称(“姓名”、“职业”、“性别”),另一个包含相应资源的 ID。它们是 String[] from, int[] to
,因此 map 中具有键 from[n]
的数据将显示在 ID 为 to 的 View 中[n]
String[] from = new String[] {"name", "gender", "occupation" };
int[] to = {R.id.name, R.id.gender, R.id.occupation }
然后您使用该列表和您的 XML 文件创建一个 SimpleAdapter
:
SimpleAdapter mAdapter = new SimpleAdapter(YourActivity.this, maps, R.layout.my_list_item, from, to);
然后在 ListActivity
中设置此适配器,列表将显示:
setListAdapter(mAdapter);
如果你想显示字符串以外的东西,你需要继承 SimpleAdapter 并重新定义一些函数,如 setViewText
、setViewImage
但我对此了解不多
关于java - ArrayAdapter<MyClass> 附加到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10586863/