一、概述
Android中经常在有的app中可以见到“加载中”并不是以弹出对话框的形式显示的,而是占用整个屏幕,如果加载失败就会出现加载失败页面,点击加载失败页面中任意区域,都可以重新加载。今天就和大家一起学习如何通过自定义view的方式实现加载中、加载失败、无数据的效果。
二、实现代码
自定义属性文件
<declare-styleable name="LoadingLayout">
<attr name="loadingView" format="reference" />
<attr name="stateView" format="reference" />
<attr name="emptyView" format="reference" />
</declare-styleable>
自定义view:LoadingLayout.java
package com.czhappy.effectdemo.loadinglayout;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.czhappy.effectdemo.R;
public class LoadingLayout extends FrameLayout {
/**
* 空数据View
*/
private int mEmptyView;
/**
* 状态View
*/
private int mStateView;
/**
* 加载View
*/
private int mLoadingView;
public LoadingLayout(Context context) {
this(context, null);
}
public LoadingLayout(Context context, AttributeSet attrs) {
this(context, attrs, -1);
}
public LoadingLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.LoadingLayout, 0, 0);
try {
mStateView = a.getResourceId(R.styleable.LoadingLayout_stateView, R.layout.loadstate_layout);
mLoadingView = a.getResourceId(R.styleable.LoadingLayout_loadingView, R.layout.loading_layout);
mEmptyView = a.getResourceId(R.styleable.LoadingLayout_emptyView, R.layout.empty_layout);
LayoutInflater inflater = LayoutInflater.from(getContext());
inflater.inflate(mStateView, this, true);
inflater.inflate(mLoadingView, this, true);
inflater.inflate(mEmptyView, this, true);
} finally {
a.recycle();
}
}
/**
* 布局加载完成后隐藏所有View
*/
@Ove