Android ListView中HeaderView和FooterView隐藏的两种方法

来源:互联网 发布:asm算法 编辑:程序博客网 时间:2024/06/01 08:26
ListView加载更多内容时,往往会用到HeaderView或FooterView。内容加载完毕或没有更多内容时,需要把HeaderView或FooterView隐藏掉,或去掉。我在公司编码时遇到这个问题,经过测试,介绍两种方法。

一、不使用布局文件。 
btnMore = new Button(this);
btnMore.setText("查看更多");

listView.addFooterView(btnMore);//addFooterView要在setAdapter之前执行一次。

listView.setAdapter(listViewAdapter);

不想显示FooterView时,可以removeFooterView。为什么这里在setAdapter之前要addFooterView呢。看一下源码就明白了。

@Override
public void setAdapter(ListAdapter adapter) {

…………

if (mHeaderViewInfos.size() > 0|| mFooterViewInfos.size() > 0) {
            mAdapter = new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, adapter);
} else {
            mAdapter = adapter;

}

…………

}

可见,当ListView没有HeaderView或FooterView时,与ListView相关联的Adapter就是传递的参数Adapter,否则,就将原来的Adapter封装成HeaderViewListAdapter。

这种方法是通过频繁的增减ListView的页眉页脚来达到显示与消失的目的,容易对Adapter带来其他问题,操作前,可以先保存下Adapter。


二、使用布局文件。

定义一个布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <LinearLayout
        android:id="@+id/layout_checkmore"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <Button
            android:id="@+id/btn_checkmore"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>

在程序中使用上述布局:

linear_footView = (LinearLayout) LayoutInflater.from(this).inflate(
R.layout.listview_footview_layout, null);
btnMore = (Button) linear_footView.findViewById(R.id.btn_checkmore);

listView.addFooterView(linear_footView);

listView.setAdapter(listViewAdapter);

然后通过btnMore.setVisibility(View.VISIBLE)和btnMore.setVisibility(View.GONE)来控制ListView页眉页脚的显示和隐藏。需要注意的是,布局中嵌套了一个LinearLayout,否则是没有作用的,就是要设置Button的根layout的Visibility属性。

原创粉丝点击