ListView中动态显示和隐藏Header&Footer

若是须要动态的显示和隐藏footer的话,按照惯例,误觉得直接经过setVisibility中的View.GONE就能够实现。可是在实际使用中发现并非这样的。

例如,先加载footer布局:php

private View mFooter; mFooter = LayoutInflater.from(this).inflate(R.layout.footer, null); //加载footer的布局 mListView.addFooterView(mFooter); 

若是想动态隐藏这个footer,惯性思惟是直接设置footer为gone:(其实这样作是不对的)java

mFooter.setVisibility(View.GONE);  //隐藏footer

实际上,直接设置GONE后,虽然元素是隐藏了,可是仍是占用着那个区域,此时和View.INVISIBILE效果同样。android

footer的正确使用方法以下:布局

一、方法一:this

(1)布局文件:在footer布局文件的最外层再套一层LinearLayout/RelativeLayout,咱们称为footerParent。spa

layout_footer_listview.xml:(完整版代码)code

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mFooterparent" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#FFFFFF" android:gravity="center" android:orientation="vertical" > <LinearLayout android:id="@+id/mFooter" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center"> <TextView android:layout_width="wrap_content" android:layout_height="40dp" android:layout_centerVertical="true" android:layout_marginLeft="10dp" android:gravity="center" android:text="查看更多" android:textColor="#ff0000" android:textSize="20sp"/> </LinearLayout> </LinearLayout> 

(2)加载footer和footerParent的布局:xml

private View mFooter; //footer private View mFooterParent; //footer的最外面再套一层LinearLayout mFooterParent = LayoutInflater.from(getActivity()).inflate(R.layout.footerparent_listview, null);//加载footerParent布局 mFooter = mFooterParent.findViewById(R.id.footer); listView.addFooterView(mFooterParent); //把footerParent放到ListView当中 mFooterParent.setOnClickListener(MainActivity.this); //绑定监听事件,点击查看所有列表

(3)设置footer为gone:(不是设置footerParent为gone)事件

mFooter.setVisibility(View.GONE);

 

二、方法二:或者直接在代码中为footer添加footerParent也能够,以下:utf-8

private View mFooter; //footer mFooter = LayoutInflater.from(getActivity()).inflate(R.layout.footer_listview, null);//加载footer布局 LinearLayout mFooterParent = new LinearLayout(context); mFooterParent.addView(mFooter);//在footer的最外面再套一层LinearLayout(即footerParent) listView.addFooterView(mFooterParent);//把footerParent放到ListView当中 

当须要隐藏footer的时候,设置footer为gone:(不是设置footerParent为gone)

mFooter.setVisibility(View.GONE);
相关文章
相关标签/搜索