原文鏈接:http://www.cnblogs.com/smyhvae/archive/2016/08/26/5810471.html
ListView的模板寫法
ListView模板寫法的完整代碼:
•android代碼優化----ListView中自定義adapter的封裝(ListView的模板寫法)
以後每寫一個ListView,就這麼做:直接導入ViewHolder.java和ListViewAdapter,然後寫一個自定義adapter繼承自ListViewAdapter就行了。
ListView中動態顯示和隱藏Header&Footer
如果需要動態的顯示和隱藏footer的話,按照慣例,誤以爲直接通過setVisibility中的View.GONE就可以實現。但是在實際使用中發現並不是這樣的。
例如,先加載footer佈局:
1
2
3
|
private
View mFooter;
mFooter
= LayoutInflater.from( this ).inflate(R.layout.footer,
null );
mListView.addFooterView(mFooter);
|
如果想動態隱藏這個footer,慣性思維是直接設置footer爲gone:(其實這樣做是不對的)
1
|
mFooter.setVisibility(View.GONE);
|
實際上,直接設置GONE後,雖然元素是隱藏了,但是還是佔用着那個區域,此時和View.INVISIBILE效果一樣。
footer的正確使用方法如下:
1、方法一:
(1)佈局文件:在footer佈局文件的最外層再套一層LinearLayout/RelativeLayout,我們稱爲footerParent。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
layout_footer_listview.xml:(完整版代碼)
<?xml
version= "1.0"
encoding= "utf-8" ?>
<LinearLayout
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的佈局:
1
2
3
4
5
6
|
private
View mFooter;
private
View mFooterParent;
mFooterParent
= LayoutInflater.from(getActivity()).inflate(R.layout.footerparent_listview,
null );
mFooter
= mFooterParent.findViewById(R.id.footer);
listView.addFooterView(mFooterParent);
mFooterParent.setOnClickListener(MainActivity. this );
|
(3)設置footer爲gone:(不是設置footerParent爲gone)
1
|
mFooter.setVisibility(View.GONE);
|
2、方法二:
或者直接在代碼中爲footer添加footerParent也可以,如下:
1
2
3
4
5
|
private
View mFooter;
mFooter
= LayoutInflater.from(getActivity()).inflate(R.layout.footer_listview, null );
LinearLayout
mFooterParent = new
LinearLayout(context);
mFooterParent.addView(mFooter);
listView.addFooterView(mFooterParent);
|
當需要隱藏footer的時候,設置footer爲gone:(不是設置footerParent爲gone)
1
|
mFooter.setVisibility(View.GONE);
|
以上所述是小編給大家介紹的Android ListView中動態顯示和隱藏Header&Footer的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對腳本之家網站的支持!