如何分配多个字段的ArrayAdapter与ListView自定义ListViewItems使用? &



我有一个ArrayList<String> taskList;,我添加字符串。然后我用

将它们连接到ArrayAdapter
if (mAdapter == null) {
mAdapter = new ArrayAdapter<>(this,
R.layout.item_todo,
R.id.task_title,
taskList);
mTaskListView.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(taskList);
mAdapter.notifyDataSetChanged();
}

item_todo.xml如下所示

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/task_title"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:text="Text"
android:layout_weight=".3"
android:textSize="20sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight=".9"
android:orientation="vertical">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
...
</LinearLayout>
<TextView
android:id="@+id/tvKategorie"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:text="Kategorie" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>

之前,没有

<TextView
android:id="@+id/tvKategorie"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:text="Kategorie" />

如何既填充task_title又填充tvKategorie的内容?

我的想法:

创建一个新的类EntryCategory,然后创建一个ArrayList<EntryCategory> taskList;,task_titletvKategorie字段。

仍然存在的问题是如何将taskListtask_titletaskListtvKategorie分配给mAdapter,以便它显示在我的列表中的每个项目中?

实现这一目标的最佳方法是使用RecyclerView。

但是如果你仍然想使用ListView,我在下面提供了许多解决方案之一:

mAdapter = new ArrayAdapter<EntryCategory>(this,
R.layout.item_todo, R.id.task_title,
taskList) {

@Override
public View getView (int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView tvTaskTitle = (TextView) view.findViewById(R.id.task_title);
TextView tvKategorie = (TextView) view.findViewById(R.id.tvKategorie);
EntryCategory item = getItem(position);
tvTaskTitle.setText(item.getTaskTitle());
tvKategorie.setText(item.getKategorie());
return view;
}
};

请原谅我的语法错误,因为我是用手机回复的。


更新:

请将R.id.task_title作为ArrayAdapter构造函数的第三个参数传递。因此,新代码将如下所示,

mAdapter = new ArrayAdapter<EntryCategory>(this,
R.layout.item_todo, R.id.task_title,
taskList) {
.....
}

最新更新