• 50个Android开发技巧(24 处理ListView数据为空的情况)


         在移动平台上为用户展示数据的一个经常用法是将数据填充进一个List内,而此时须要注意的一点就是:
    原文地址:(http://blog.csdn.net/vector_yi/article/details/24936163)
              怎样处理须要填充的数据为空的情况?
       
          ListView及其它继承自AdapterView的类都有一个简便的处理这样的情况的方法:setEmptyView(View)
         当ListView的Adapter为空或者Adapter的isEmpty()方法返回true的时候,它将会把设置的emptyview绘制出来。

         举个栗子,如果我们须要创建一个应用来管理我们的待办事项,我们的主页面将会是一个用来展示这些待办事项的ListView。
         而当我们第一次加载进这个应用时,待办事项必定为空。此时我们就能够利用一个图片或者一段描写叙述性的话来表达“无待办事项”。
         看看XML布局文件:
     <FrameLayout xmlns:android = "http://schemas.android.com/apk/res/android"
        android:layout_width= "fill_parent"
        android:layout_height= "fill_parent"
        android:orientation= "vertical" >
    
        <ListView
            android:id ="@+id/my_list_view"
            android:layout_width ="fill_parent"
            android:layout_height ="fill_parent" />
    
        <ImageView
            android:id ="@+id/empty_view"
            android:layout_width ="fill_parent"
            android:layout_height ="fill_parent"
            android:src ="@drawable/empty_view" />
    
    </FrameLayout>
    

    再来看自己定义的drawable/empty_view文件:
    <shape xmlns:android = "http://schemas.android.com/apk/res/android"
        android:shape= "rectangle" >
        <solid android:color= "#AA00FF00" />
    </shape>
    
         是一个自己定义的shape,当ListView没数据的时候才展现出来。

         最后再看MainActivity文件:
    public class MainActivity extends Activity {
    
      private ListView mListView;
    
      @Override
      public void onCreate (Bundle savedInstanceState ) {
        super. onCreate( savedInstanceState );
        setContentView (R .layout .main );
    
        mListView = (ListView ) findViewById (R .id .my_list_view );
        mListView. setEmptyView (findViewById (R .id .empty_view ));
        /*String[] strs=new String[]{"1","2"};
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,strs);
        mListView.setAdapter(adapter);*/
       
      }
    
    }
    

        只创建一个ListView并设置了EmptyView为main.xml中创建的ImageView。凝视内的代码用来測试当ListView有数据时,emptyview会不会显示。

         当然,你能够利用ViewStub来作为EmptyView,利用ViewStub能够延迟载入视图,确保在不须要显示EmptyView的时候它不会被渲染。关于ViewStub的使用方法,我在之前的博文《延迟载入和避免反复渲染》已进行过叙述。



  • 相关阅读:
    构造代码块重要理解
    Java中静态代码块、构造代码块、构造函数、普通代码块
    MySQL-分组查询(GROUP BY)及二次筛选(HAVING)
    mysql select将多个字段横向合拼到一个字段
    java语言支持的变量类型
    static修饰属性,方法,类
    恶意代码分析----网络环境配置
    Windows反调试技术(下)
    Windows反调试技术(上)
    脱壳入门----常见的寻找OEP的方法
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/3795368.html
Copyright © 2020-2023  润新知