温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

快速处理ListView为空的情况

发布时间:2020-09-07 13:41:00 来源:脚本之家 阅读:182 作者:jingxian 栏目:移动开发

在移动开发中经常会使用到列表显示,对于列表显示我们经常使用的就是ListView控件。在显示列表的时候通常有两种情况:

一、列表是满的;

二、列表是空的;

在没有数据的时候我们应该怎么处理呢?有一个简单的方法可以解决问题,我们来看一下。

ListView和其他继承自AdapterView的类可以使用setEmptyView(View view)方法设置空状态下的显示。当绘制AdapterView的适配器为空或者isEmpty方法返回true,此时就会显示setEmptyView(View view)方法设置的视图。

例如:我们在界面上显示如下视图。

<?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,注意我在测试的时候发现ImageView一定设置android:visibility=”gone”否则不管ListView的适配器是否为空都会显示。

在Activity中我们可以这样设置:

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

这样当我们的数据为空的时候可以把empty_listview_lv.setAdapter(null);这样就会显示ImageView(注:不需要把ImageView的visibility设置为可见);

附:有数据显示

快速处理ListView为空的情况

没有数据情况显示

快速处理ListView为空的情况

以上这篇快速处理ListView为空的情况就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI