Android自定义view实现加载中、加载失败、无数据

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 继承FrameLayout (帧布局)LoadingLayout

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
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        for (int i = 0; i < getChildCount() - 1; i++) {
            getChildAt(i).setVisibility(GONE);
        }
    }


    /**
     * 设置Empty点击事件
     * @param listener
     */
    public void setEmptyClickListener(final OnClickListener listener) {
        if( listener!=null )
            findViewById(R.id.state_retry2).setOnClickListener(listener);
    }

    /**
     * 设置State点击事件
     * @param listener
     */
    public void setStateClickListener( OnClickListener listener ){
        if(listener!=null)
            findViewById(R.id.state_retry).setOnClickListener(listener);
    }

    /**
     * 设置自定义布局的点击事件
     * @param resoureId
     * @param listener
     */
    public void setViewOncClickListener(int resoureId,OnClickListener listener) {
        findViewById(resoureId).setOnClickListener(listener);
    }

    /**
     * 设置自定义布局的view文本
     * @param resoureId
     * @param text
     */
    public void setViewText(int resoureId,String text){
        ((TextView)findViewById(resoureId)).setText(text);
    }

    /**
     * 设置自定义布局的image
     * @param resoureId
     * @param img
     */
    public void setViewImage(int resoureId,int img ){
        ((ImageView)findViewById(resoureId)).setImageResource(img);
    }

    /**
     * State View数据加载界面
     */
    public void showState() {
        for (int i = 0; i < this.getChildCount(); i++) {
            View child = this.getChildAt(i);
            if (i == 0) {
                child.setVisibility(VISIBLE);
            } else {
                child.setVisibility(GONE);
            }
        }
    }

    /**
     * Empty view 暂无数据加载界面
     */
    public void showEmpty() {
        for (int i = 0; i < this.getChildCount(); i++) {
            View child = this.getChildAt(i);
            if (i == 2) {
                child.setVisibility(VISIBLE);
            } else {
                child.setVisibility(GONE);
            }
        }
    }


    /**
     * Loading view数据加载中界面
     */
    public void showLoading() {
        for (int i = 0; i < this.getChildCount(); i++) {
            View child = this.getChildAt(i);
            if (i == 1) {
                child.setVisibility(VISIBLE);
            } else {
                child.setVisibility(GONE);
            }
        }
    }


    /**
     *
     * @param text
     */
    public void showLoading(String text) {
        for (int i = 0; i < this.getChildCount(); i++) {
            View child = this.getChildAt(i);
            if (i == 1) {
                child.setVisibility(VISIBLE);
                ((TextView) child.findViewById(R.id.loading_text)).setText(text + "");
            } else {
                child.setVisibility(GONE);
            }
        }
    }


    /**
     * Empty view 暂无数据加载界面有参数  文字提示框
     *
     * @param text
     */
    public void showEmpty(String text) {
        for (int i = 0; i < this.getChildCount(); i++) {
            View child = this.getChildAt(i);
            if (i == 2) {
                child.setVisibility(VISIBLE);
                ((TextView) child.findViewById(R.id.empty_text)).setText(text + "");
            } else {
                child.setVisibility(GONE);
            }
        }
    }


    /**
     *
     * @param tips
     */
    public void showState(String tips) {
        for (int i = 0; i < this.getChildCount(); i++) {
            View child = this.getChildAt(i);
            if (i == 0) {
                child.setVisibility(VISIBLE);
                ((TextView) child.findViewById(R.id.load_state_tv)).setText(tips + "");
            } else {
                child.setVisibility(GONE);
            }
        }
    }

    /**
     * @param stateId
     * @param tips
     */
    public void showState(int stateId, String tips) {
        for (int i = 0; i < this.getChildCount(); i++) {
            View child = this.getChildAt(i);
            if (i == 0) {
                child.setVisibility(VISIBLE);
                ((ImageView) child.findViewById(R.id.load_state_img)).setImageResource(stateId);
                ((TextView) child.findViewById(R.id.load_state_tv)).setText(tips + "");
            } else {
                child.setVisibility(GONE);
            }
        }
    }



    /**
     * 展示内容
     */
    public void showContent() {
        for (int i = 0; i < this.getChildCount(); i++) {
            View child = this.getChildAt(i);
            if (i > 2 ) {
                child.setVisibility(VISIBLE);
            } else {
                child.setVisibility(GONE);
            }
        }
    }


}

正在加载的布局文件loading_layout.xml 以及loadstate_layout加载失败重新加载  ,  enty_layout 在我这里代表服务器异常。

加载中代码Loading_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:wheel="http://schemas.android.com/apk/res-auto"
    android:id="@+id/loading_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">
 <com.pnikosis.materialishprogress.ProgressWheel
        android:id="@+id/progress_wheel"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        wheel:matProg_barColor="#5588FF"
        wheel:matProg_progressIndeterminate="true" />
<TextView android:id="@+id/loading_text" android:layout_width="wrap_content" android:padding="5dp" android:layout_height="wrap_content" android:text=" 正在加载..." android:textColor="#999999" android:textSize="15sp" /></LinearLayout>

loadstate_layout加载失败重新加载

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:wheel="http://schemas.android.com/apk/res-auto"
    android:id="@+id/state_retry"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/load_state_img"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@mipmap/ic_launcher"/>

    <TextView
        android:id="@+id/load_state_tv"
        android:layout_width="wrap_content"
        android:padding="5dp"
        android:layout_height="wrap_content"
        android:text="数据加载失败,点击重试..."
        android:textColor="#999999"
        android:textSize="15sp"/>


</LinearLayout>
 enty_layout 服务器异常
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:wheel="http://schemas.android.com/apk/res-auto"
    android:id="@+id/state_retry2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/progress_wheel"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@mipmap/ic_launcher_round"/>

    <TextView
        android:id="@+id/empty_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" 服务器加载异常,稍后再试!"/>

</LinearLayout>

最后我们在MainActivity中测试 

public class LoadingLayoutActivity extends AppCompatActivity implements View.OnClickListener{

    private Button btn1, btn2, btn3;
    private LoadingLayout mLoading;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1000){
                mLoading.showContent();
            }else if(msg.what==2000){
                mLoading.showState("加载失败,点击重试!");
            }else if(msg.what==3000){
                mLoading.showEmpty();
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading_layout);

        initView();
    }

    private void initView() {
        mLoading = (LoadingLayout) findViewById(R.id.loading_layout);
        btn1 = (Button) findViewById(R.id.btn1);
        btn2 = (Button) findViewById(R.id.btn2);
        btn3 = (Button) findViewById(R.id.btn3);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        mLoading.showContent();
        mLoading.setStateClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLoading.showLoading();
                mLoading.postDelayed(new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        //模拟网络请求
                        mHandler.sendEmptyMessage(2000);
                    }
                },1000);
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn1:
                mLoading.showLoading();
                mLoading.postDelayed(new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        //模拟网络请求
                        mHandler.sendEmptyMessage(1000);
                    }
                },2000);
                break;
            case R.id.btn2:
                mLoading.showLoading();
                mLoading.postDelayed(new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        //模拟网络请求
                        mHandler.sendEmptyMessage(2000);
                    }
                },2000);
                break;
            case R.id.btn3:
                mLoading.showLoading();
                mLoading.postDelayed(new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        //模拟网络请求
                        mHandler.sendEmptyMessage(3000);
                    }
                },2000);
                break;
        }
    }
}

项目中实现正在加载的material design风格的进度动画,用的是开源库 
https://github.com/pnikosis/materialish-progress 
如果你有其他需求,可以自己替换

这里写图片描述

借鉴于也非常感谢博主的辛勤努力:https://blog.csdn.net/chenzheng8975/article/details/56282131

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值