【问题标题】:ArrayAdapter and ListView display only specific itemsArrayAdapter 和 ListView 仅显示特定项目
【发布时间】:2011-09-30 16:43:41
【问题描述】:

我正在尝试开发一个学校规划器应用程序。有一个时间表概览实现为包含在选项卡布局中的每一天的 ListView。因此,用户可以在周一到周五之间切换,并获取特定日期的时间表。

public class TimetableAdapter extends ArrayAdapter<Lesson> {
    private List<Lesson> lessonList; // The model

...

public View getView(int position, View convertView, ViewGroup parent) {
    View view = null;
    ...
    view = inflater.inflate(R.layout.timetable_row, null);
    Lesson currentLesson = lessonList.get(position);

    // Checks if selected Tab (context.getDay()) correspondends to 
    // currentLesson's day. If so the lesson will be rendered into
    // the appropriated ListView. So if the user selects the Monday Tab 
    // he only wants to see the lessons for Monday.
    if (context.getDay() == currentLesson.getWeekDay().getWeekDay()) {
        fillView(currentLesson, holder); // render Lesson
    }
    ...
    return view;
}

private void fillView(Lesson currentLesson, ViewHolder holder) {
    holder.subject.setText(currentLesson.getSubject().getName());
}

public class TimetableActivity extends Activity implements OnTabChangeListener {
    public void onCreate(Bundle savedInstanceState) {
        ....
        timetableAdapter = new TimetableAdapter(this, getModel());
    }

private List<Lesson> getModel() {
    return timetable.getLessons();
}

public void onTabChanged(String tabId) {
    currentTabName = tabId;
    if (tabId.equals("tabMonday")) {
    setCurrentListView(mondayListView);
    }
    else if (tabId.equals("tabTuesday")) { 
        // Checks tabTuesday and so on....
        ...
    }
 }    
private void addLesson() {
    timetable.addLesson(new Lesson(blabla(name, weekday etc.))); // blabla = user specified values
    timetableAdapter.notifyDataSetChanged();
}

因此,基本上,如果用户添加课程,他会指定一些参数,例如相应的工作日、名称等。这由 blabla 表示。

问题在于,因为我只使用一个 ArrayList 来存储我的数据,所以无论是周一的主题还是周二的课程,例如对于星期一在我星期二的 ListView 上呈现为空行,因为 getView(...) 为课程列表中的每个项目调用,它只返回一个 new View(),如果工作日不是所需的,我认为。

一种解决方案可能是为适当的工作日创建 5 个 ArrayList 和 5 个 ArrayAdapter。所以周一的课会在ArrayList mondayList,适配器会绑定到这个列表。但这有点不灵活。 有没有更好的解决方案?

提前致谢。

【问题讨论】:

    标签: android listview arraylist android-arrayadapter


    【解决方案1】:

    不要使用 ArrayAdapter,而是使用 SimpleAdapter。对于您想要显示的内容,它要灵活得多。其次,将所有约会的 ArrayList 保留在适配器之外,创建某种过滤方法来复制适用的对象并将这个新列表传递给 SimpleAdapter。

    【讨论】:

    • 好的。谢谢你。该解决方案似乎相对容易实施。我试试看。
    • 顺便说一下,您只需要复制引用,而不需要复制对象的深层副本。
    猜你喜欢
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 2014-08-20
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多