当前位置: 移动技术网 > 移动技术>移动开发>Android > Android ListView中动态显示和隐藏Header&Footer的方法

Android ListView中动态显示和隐藏Header&Footer的方法

2019年07月24日  | 移动技术网移动技术  | 我要评论

listview的模板写法

listview模板写法的完整代码:

•android代码优化----listview中自定义adapter的封装(listview的模板写法)

以后每写一个listview,就这么做:直接导入viewholder.java和listviewadapter,然后写一个自定义adapter继承自listviewadapter就行了。

listview中动态显示和隐藏header&footer

如果需要动态的显示和隐藏footer的话,按照惯例,误以为直接通过setvisibility中的view.gone就可以实现。但是在实际使用中发现并不是这样的。

例如,先加载footer布局:

private view mfooter;
mfooter = layoutinflater.from(this).inflate(r.layout.footer, null); //加载footer的布局
mlistview.addfooterview(mfooter);

如果想动态隐藏这个footer,惯性思维是直接设置footer为gone:(其实这样做是不对的)

mfooter.setvisibility(view.gone); //隐藏footer

实际上,直接设置gone后,虽然元素是隐藏了,但是还是占用着那个区域,此时和view.invisibile效果一样。

footer的正确使用方法如下:

1、方法一:

(1)布局文件:在footer布局文件的最外层再套一层linearlayout/relativelayout,我们称为footerparent。

layout_footer_listview.xml:(完整版代码)
<?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的布局:

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);

2、方法二:

或者直接在代码中为footer添加footerparent也可以,如下:

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);

以上所述是小编给大家介绍的android listview中动态显示和隐藏header&footer的方法,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网