状态切换:自定义View之StatusView

本文介绍了一种自定义View的方法,可以实现不同状态的动态展示,包括加载中、数据为空、加载失败、网络错误和加载完成五种状态。该View通过直接绘制不同状态视图来减少布局层级,提供了一种轻量级的状态展示方案。

介绍

一个自定义View,用于切换不同状态。这个轮子已经有很多人造过,不过,我发现基本都是自定义FrameLayout、LinearLayout或是RelativeLayout,然后编写layout_error,layout_empty等布局,加载进去。那就有一个问题,我们在使用的时候,无形中就增加了一个布局层级。所以,偶就想,能不能直接自定义一个View,动态draw不同的状态视图。欲知详情,且请慢慢往下看。

效果图

基本用法

1、StatusView一共有5种状态

【1】正在加载:显示环形进度条和文字提示 mStatusView.isLoading();
【2】数据为空:显示图标和文字提示 mStatusView.isEmpty();
【3】加载失败:显示图标和文字提示 mStatusView.isNoNetwork();
【4】网络错误:显示图标和文字提示 mStatusView.isError();
【5】加载完成:不显示 mStatusView.isFinished();
复制代码

2、使用方法:在xml布局中直接添加,默认显示加载视图,调用StatusVuew的方法修改不同状态。当调用isFinished()方法时会隐藏StatusView。

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.jiangyy.statussample.MainActivity">

    <android.support.v7.widget.AppCompatTextView
        android:id="@+id/tvContent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:onClick="testClick"
        android:text="显示的数据"/>

    <com.jiangyy.statusview.StatusView
        android:id="@+id/statusView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</FrameLayout>
复制代码

3、自定义属性

<resources>
    <declare-styleable name="StatusView">
        <!--- 文本文字大小 -->
        <attr name="textSize" format="dimension"/>
        <!--- 文本文字颜色 -->
        <attr name="textColor" format="color"/>
        <!--- 空状态显示图标 -->
        <attr name="emptyIcon" format="reference"/>
        <!--- 加载失败显示图标 -->
        <attr name="errorIcon" format="reference"/>
        <!--- 网络错误显示图标 -->
        <attr name="noNetWorkIcon" format="reference"/>
    </declare-styleable>
</resources>
复制代码

附上Github地址 StatusView

项目已上传至Jcenter,可以直接引入使用:

dependencies {
    // ... other dependencies here
    implementation 'com.jiangyy:statusview:1.0.0'
}
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值