您好,登錄后才能下訂單哦!
在移動開發(fā)中經(jīng)常會使用到列表顯示,對于列表顯示我們經(jīng)常使用的就是ListView控件。在顯示列表的時候通常有兩種情況:
一、列表是滿的;
二、列表是空的;
在沒有數(shù)據(jù)的時候我們應(yīng)該怎么處理呢?有一個簡單的方法可以解決問題,我們來看一下。
ListView和其他繼承自AdapterView的類可以使用setEmptyView(View view)方法設(shè)置空狀態(tài)下的顯示。當(dāng)繪制AdapterView的適配器為空或者isEmpty方法返回true,此時就會顯示setEmptyView(View view)方法設(shè)置的視圖。
例如:我們在界面上顯示如下視圖。
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/empty_listview_lv" android:layout_width="match_parent" android:layout_height="match_parent" /> <ImageView android:id="@+id/empty_imageview_iv" android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/bg" android:visibility="gone"/> </FrameLayout>
在ListView下顯示一個ImageView,注意我在測試的時候發(fā)現(xiàn)ImageView一定設(shè)置android:visibility=”gone”否則不管ListView的適配器是否為空都會顯示。
在Activity中我們可以這樣設(shè)置:
public class EmptyListViewActivity extends Activity { private ListView empty_listview_lv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.empty_listview_layout); empty_listview_lv = (ListView) findViewById(R.id.empty_listview_lv); String[] mListStr = {"1","2","3","3","4"}; empty_listview_lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, mListStr)); empty_listview_lv.setEmptyView(findViewById(R.id.empty_imageview_iv)); } }
這樣當(dāng)我們的數(shù)據(jù)為空的時候可以把empty_listview_lv.setAdapter(null);這樣就會顯示ImageView(注:不需要把ImageView的visibility設(shè)置為可見);
附:有數(shù)據(jù)顯示
沒有數(shù)據(jù)情況顯示
以上這篇快速處理ListView為空的情況就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。