我有一个自定义适配器用于我的ListView我想将项目名称作为标题添加到我的工作请求中.添加单个标头工作正常,但我不知道如何使用addHeaderView添加多个标头.我不明白究竟放置setAdapter的位置,还是应该放置多次?
mListView = (ListView)findViewById(R.id.dashboardList); View header1 = getLayoutInflater().inflate(R.layout.listview_header,null,false); tv = (TextView) header1.findViewById(R.id.listHeader); adapter = new MyCustomAdapter(MyDashboardActivity.this,R.layout.mydashboard_row,dashboardBean); tv.setText("Project 1"); mListView.addHeaderView(header1,false); for (int i=0; i < 7; i++) { dashboardBean.add(new DashboardBean(workRequests[i],status[i],actualHours[i])); } mListView.setAdapter(adapter);
现在,我尝试了两个标题:
mListView = (ListView)findViewById(R.id.dashboardList); View header1 = getLayoutInflater().inflate(R.layout.listview_header,dashboardBean); tv.setText("RxOffice"); mListView.addHeaderView(header1,false); for (int i=0; i < 4; i++) { dashboardBean.add(new DashboardBean(workRequests[i],actualHours[i])); } tv.setText(Project 2"); mListView.addHeaderView(header1,false); for (int i=4; i < workRequests.length; i++) { dashboardBean.add(new DashboardBean(workRequests[i],actualHours[i])); } mListView.setAdapter(adapter);
但这不起作用!它只给我Project 2标题和它下面的所有7个条目.谁能告诉我有什么问题?我猜它与setAdapter有关.谢谢!
解决方法
我不认为你想做的事情可能就像你想要做的那样.当您使用addHeaderView时,它会将您的ListAdapter包装在HeaderViewListAdapter中.我查看了它的文档
here,这似乎意味着你可以有多个标题,但它们都会在顶部(duh,header).
这听起来像你真正想要的是分离器……
您可以使用CommonWare’s MergeAdapter.它将允许您插入适配器和视图(以您希望的任何顺序)并将它们作为单个适配器呈现给列表视图.您只需为每个内容部分提供标题和适配器,然后将其设置为列表.
伪代码示例:
myMergeAdapter = new MergeAdapter(); myMergeAdapter.addView(HeaderView1); myMergeAdapter.addAdapter(listAdapter1); myMergeAdapter.addView(HeaderView2); myMergeAdapter.addAdapter(listAdapter2); setListAdapter(myMergeAdapter);