Android showing LoadingView or EmptyView for Activity or Fragment

这几天利用一些时间,整理了一下,写了一个简单的工具类,用来快速的显示LoadingView或者EmptyView,以前都是定义一个layout,根布局为FrameLayout,再在layout布局文件里面添加LoadingView或者EmptyView,然后在Activity里面设置visible属性,代码太冗余,所以在这种情况下催生了我这个小项目;

代码拖管地址:

https://github.com/a284628487/EasyLoading

 

现在使用这个工具类,一切都变得很简单,不需要再在Activity中或者Fragment中去定义一个成员变量,然后初始化、显示、隐藏;

现在只需要一句代码就搞定

显示LoadingView

ActivityTool.showLoading(Activity activity, int layoutId)
ActivityTool.showLoading(Activity activity, View view)
ActivityTool.showLoading(Activity activity, int layoutId, boolean dimBackground)
ActivityTool.showLoading(Activity activity, View view, boolean dimBackground)

显示EmptyView

ActivityTool.showEmpty(Activity activity, int layoutId)
ActivityTool.showEmpty(Activity activity, View view)

隐藏LoadingView或EmptyView

ActivityTool.dismiss(Activity activity)

  显示的时候,只需要传入你要显示的view或者一个layoutid,LoadingView / EmptyView就显示出来了,看到这里,可能有人会想,那我还不是得传入一个View或者定义一个layout布局,确实如此。但是,在这种情况下,我们的LoadingView / EmptyView和Activity和Fragment是分开管理了的,没有任何关联,在你的Activity中和Fragment中,是看不到LoadingView / EmptyView的,也不需要在layout中定义多个ViewStub,使Fragment和Activity更加纯净,没有干扰信息;

 

注意:在Fragment中使用时,要求Fragment的所持有的view为FrameLayout,有两种方法,参见上面github代码托管地址;

  To showing LoadingView or EmptyView in a Fragment, the Fragment’s rootView must be a FrameLayout or FrameLayout’s subclass, you can define a xml-layout which rootView is FrameLayout for the Fragment or just make your Fragment extends LoadingSupportFragment / LoadingFragment and achieve the method contentViewLayoutId() to return your xml-layoutId, and you don’t need to override the method onCreateView(); yeah, you can show the EmptyView or LoadingView simply; 

  为了让Fragment能够显示LoadingView或EmptyView,Fragment所创建的view必须是FrameLayout或者FrameLayout的子类,这里有两种快捷的方法,一是同往常一样,定义一个layout布局文件然后让Fragment创建view,但该layout的rootView必须为FrameLayout;二是继承LoadingFragment或者LoadingSupportFragment,并且实现方法contentViewLayoutId(),在该方法中返回自定义的layout布局文件,该布局文件则没有rootView的限制,rootView可以是任意的控件,并且,使用这种方法也就不需要再重写Fragment的onCreateView方法;

 

posted @ 2015-09-21 21:39  Livingstone  阅读(577)  评论(1编辑  收藏  举报