在开发中我们常常有向ListView中添加header的需求,并且这个ListView还要提供下拉刷新的功能。下拉刷新库Android-PullToRefresh是个不错的下拉刷新库,不但支持ListView,还支持GridView,WebView,ScrollView。但是当我想向PullToRefreshListViews中添加header的时候我并没有找到addHeaderView方法。后来发现PullToRefreshListViews其实不是ListView的子类。他里边持有ListView对象。因而我找到了下边的代码来添加了1个header.
mInviteRecordLv = (PullToRefreshListView) findViewById(R.id.invest_record_list);
View header = getLayoutInflater().inflate(R.layout.invite_record_header, mInviteRecordLv, false);
ListView lv = mInviteRecordLv.getRefreshableView();
lv.addHeaderView(header);
mInviteRecordLv.setAdapter(new InviteRecordAdapter(this));
我以为向上边那样写应当就没有问题了,但是当我运行程序的时候出现了以下毛病:
java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
后来把代码改成下边这样成功得到了我要的结果
mInviteRecordLv = (PullToRefreshListView) findViewById(R.id.invest_record_list);
AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT);
View header = getLayoutInflater().inflate(R.layout.invite_record_header, mInviteRecordLv, false);
header.setLayoutParams(layoutParams);
ListView lv = mInviteRecordLv.getRefreshableView();
lv.addHeaderView(header);
mInviteRecordLv.setAdapter(new InviteRecordAdapter(this));
Android-PullToRefresh库的下载地址:https://github.com/chrisbanes/Android-PullToRefresh