状态布局StateLayout

public class StateLayout extends FrameLayout {

    private View mLoadingView;
    private View mEmptyView;
    private View mNormalView;
    private View mErrorView;

    public void setOnErrorClickListener(OnErrorClick onErrorClick) {
        this.onErrorClick = onErrorClick;
    }

    private OnErrorClick onErrorClick;



    /***
     * 构造方法
     */
    public StateLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // 加载 到当前的布局
        View view = View.inflate(context, R.layout.view_statelayout, null);
        mErrorView = view.findViewById(R.id.state_error);
        mEmptyView = view.findViewById(R.id.state_empty);
        mLoadingView = view.findViewById(R.id.state_loading);
        // 添加当前的容器
        addView(view);
    }

    public StateLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public StateLayout(Context context) {
        this(context, null, 0);
    }

    // 对四种网络状态的show
    public void showErrorView() {
        resetState();
        // 重置四种状态,
        mErrorView.setVisibility(View.VISIBLE);
        mErrorView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onErrorClick != null) {
                    onErrorClick.onClick(v);
                }
            }
        });
    }

    public void showLoadingView() {
        resetState();
        // 重置四种状态,
        mLoadingView.setVisibility(View.VISIBLE);
    }

    public void showEmptyView() {
        resetState();
        // 重置四种状态,
        mEmptyView.setVisibility(View.VISIBLE);
    }

    protected void resetState() {
        if (mNormalView != null) {
            mNormalView.setVisibility(View.GONE);
        }

        mErrorView.setVisibility(View.GONE);
        mEmptyView.setVisibility(View.GONE);
        mLoadingView.setVisibility(View.GONE);
    }


    // 扩充原因:因为每一个页面,获取正常数据的展示不一样。就不能写死在布局,而是使用代码动态设置
    public void setNormalView(int layoutId) {
        mNormalView = View.inflate(getContext(), layoutId, null);
        mNormalView.setVisibility(View.GONE);
        // 添加后者是当前布局容器的元素
        addView(mNormalView);
    }

    public void setNormalView(View normalView) {
        mNormalView = normalView;
        mNormalView.setVisibility(View.GONE);
        // 添加后者是当前布局容器的元素
        addView(mNormalView);
    }

    public void showNormal() {
        resetState();
        // 重置四种状态,
        if (mNormalView != null) {
            mNormalView.setVisibility(View.VISIBLE);
        }
    }
}

你可能感兴趣的:(状态布局StateLayout)