Android 自定義一款炫酷的加載控件

概述:

在設計應用的時候,我們應該熱愛極簡主義,簡單就是好的,對于很多用戶來說,復雜的東西并不受歡迎。
我要實現的是根據不同的情況去顯示不同的加載效果,隨用隨調,效果是借鑒于某一項目的效果,我認為有必要提取出來改善封裝一下,供以后使用。情況大致分為:加載中、無網絡、無數據、加載失敗等;

預覽下效果圖

這里寫圖片描述

我們怎么實現這種效果呢

view_loading.xml的布局如下:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/lin_loading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="gone"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/img_loading"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:src="@drawable/loading_animation" />

        <TextView
            android:id="@+id/tv_loading"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_gravity="center_horizontal"
            android:textSize="14sp" />

    </LinearLayout>


    <LinearLayout
        android:id="@+id/lin_load"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="visible"

        >

        <ImageView
            android:id="@+id/iv_load"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:src="@mipmap/ic_launcher" />

        <TextView
            android:id="@+id/tv_load"
            android:layout_width="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_height="wrap_content" />


        <Button
            android:id="@+id/btn_load"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_gravity="center_horizontal"
            android:textSize="14sp" />

    </LinearLayout>

</FrameLayout>

從布局來看,我分了兩個部分,一個是加載中,另外一個是帶有ImagView、文字和按鈕的布局,有人看到這,就會說,哇靠,這不是很簡單嗎?根據不同的情況去設置Visibility的值就好了啊,沒錯,原理就是這樣。

XHLoadingView.java的代碼如下:

package com.woyou.loadingdemo.widget;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.woyou.loadingdemo.LoadingState;
import com.woyou.loadingdemo.R;


/**
 * Created by Xiho on 11:21.
 */
public class XHLoadingView extends FrameLayout {

    private Context mContext;
    // 加載中的布局
    private LinearLayout mLinearLoad;
    //其他加載的布局
    private LinearLayout mLinearLoading;

    private TextView mTvLoading;

    private TextView mTvLoad;

    private ImageView mIvLoading;

    private ImageView mIvLoad;

    private Button mBtnLoad;

    private LoadingState mState;

    private AnimationDrawable animation;


    public XHLoadingView(Context context) {
        super(context);
        mContext = context;
    }

    public XHLoadingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    public XHLoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
    }

    public XHLoadingView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        mContext = context;

    }
    public void build(){
        LayoutInflater.from(mContext).inflate(R.layout.view_loading, this, true);

        mLinearLoading = (LinearLayout) findViewById(R.id.lin_loading);

        mLinearLoad = (LinearLayout) findViewById(R.id.lin_load);

        mIvLoading = (ImageView) findViewById(R.id.img_loading);

        mIvLoad = (ImageView) findViewById(R.id.iv_load);

        mTvLoading = (TextView) findViewById(R.id.tv_loading);

        mTvLoad = (TextView) findViewById(R.id.tv_load);

        mBtnLoad = (Button) findViewById(R.id.btn_load);

        mBtnLoad.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setState(LoadingState.STATE_LOADING);
                mOnRetryListener.onRetry();
            }
        });

    }


    @Override
    public void setVisibility(int visibility) {
        super.setVisibility(visibility);
        if(View.GONE==visibility && mState==LoadingState.STATE_LOADING && animation!=null&&animation.isRunning()){
            animation.stop();
        }
    }

    /**
     * 加載中提示文字
     */
    private String mLoadingText;
    private int mLoadingIcon;
    public XHLoadingView withLoadingIcon(int resId){
        mLoadingIcon = resId;
        return this;
    }

    /**
     * 加載數據為空提示文字
     */
    private String mLoadEmptyText;
    private int mLoadEmptyIcon;
    public XHLoadingView withEmptyIcon(int resId){
        mLoadEmptyIcon = resId;
        return this;
    }

    /**
     * 無網絡提示
     */
    private String mLoadNoNetworkText;
    private int mNoNetworkIcon;
    public XHLoadingView withNoNetIcon(int resId){
        mNoNetworkIcon = resId;
        return this;
    }

    private OnRetryListener mOnRetryListener;

    /**
     * 定義重試的的接口
     */
    public interface OnRetryListener {
        void onRetry();
    }

    public XHLoadingView withOnRetryListener(OnRetryListener mOnRetryListener){
        this.mOnRetryListener = mOnRetryListener;
        return this;
    }

    /**
     *  設置加載的狀態
     * @param state
     */
    public void setState(LoadingState state){
        if(mState==state){
            return;
        }else if(state==LoadingState.STATE_LOADING){
            mLinearLoading.setVisibility(VISIBLE);
            mLinearLoad.setVisibility(GONE);
        }else if(state!=LoadingState.STATE_LOADING){
            mLinearLoading.setVisibility(GONE);
            mLinearLoad.setVisibility(VISIBLE);
            if(animation!=null && mState==LoadingState.STATE_LOADING)
                animation.stop();
        }
        changeState(state);
    }


    public boolean btnEmptyEnable = true;
    public boolean btnErrorEnable = true;
    public boolean btnNoNetworkEnable = true;

    public XHLoadingView withBtnNoNetEnnable(boolean ennable) {
        btnNoNetworkEnable = ennable;
        return this;
    }

    public XHLoadingView withBtnErrorEnnable(boolean ennable) {
        btnErrorEnable = ennable;
        return this;
    }


    public XHLoadingView withBtnEmptyEnnable(boolean ennable) {
        btnEmptyEnable = ennable;
        return this;
    }

    /**
     * 改變狀態
     * @param state
     */
    private void changeState(LoadingState state) {
        switch (state) {
            //加載中
            case STATE_LOADING:
                mState = LoadingState.STATE_LOADING;
                mIvLoading.setImageResource(mLoadingIcon);
                mTvLoading.setText(mLoadingText);
                if (animation == null) {
                    animation = (AnimationDrawable) mIvLoading.getDrawable();
                }
                if (animation != null)
                    animation.start();
                break;
            //數據為空
            case STATE_EMPTY:
                mState = LoadingState.STATE_EMPTY;
                mIvLoad.setImageResource(mLoadEmptyIcon);
                mTvLoad.setText(mLoadEmptyText);
                if (btnEmptyEnable) {
                    mBtnLoad.setVisibility(VISIBLE);
                    mBtnLoad.setText(btn_empty_text);
                } else {
                    mBtnLoad.setVisibility(GONE);
                }
                break;
            //加載失敗
            case STATE_ERROR:
                mState = LoadingState.STATE_ERROR;
                mIvLoad.setImageResource(mErrorIco);
                mTvLoad.setText(mLoadErrorText);
                if (btnErrorEnable) {
                    mBtnLoad.setVisibility(VISIBLE);
                    mBtnLoad.setText(btn_error_text);
                } else {
                    mBtnLoad.setVisibility(GONE);
                }
                break;
            //無網絡
            case STATE_NO_NET:
                mState = LoadingState.STATE_NO_NET;
                mIvLoad.setImageResource(mNoNetworkIcon);
                mTvLoad.setText(mLoadNoNetworkText);
                if (btnNoNetworkEnable) {
                    mBtnLoad.setVisibility(VISIBLE);
                    mBtnLoad.setText(btn_nonet_text);
                } else {
                    mBtnLoad.setVisibility(GONE);
                }
                break;
        }

    }


    /**
     * 后臺或者本地出現錯誤提示
     */
    private String mLoadErrorText;
    private int mErrorIco;

    public XHLoadingView withErrorIco(int resId) {
        mErrorIco = resId;
        return this;
    }

    /**
     * 加載空數據
     * @param resId
     * @return
     */
    public XHLoadingView withLoadEmptyText(int resId) {
        mLoadEmptyText = getResources().getString(resId);
        return this;
    }

    public XHLoadingView withLoadEmptyText(String mLoadEmptyText) {
        this.mLoadEmptyText = mLoadEmptyText;
        return this;
    }

    /**
     *  無網絡時候加載文字
     * @param resId
     * @return
     */
    public XHLoadingView withLoadNoNetworkText(int resId) {
        mLoadNoNetworkText = getResources().getString(resId);
        return this;
    }

    public String btn_empty_text = "重試";
    public String btn_error_text = "重試";
    public String btn_nonet_text = "重試";

    /**
     * 數據為空的Button的文字提示
     * @param text
     * @return
     */
    public XHLoadingView withBtnEmptyText(String text) {
        this.btn_empty_text = text;
        return this;
    }

    /**
     * 加載錯誤的Button的文字提示
     * @param text
     * @return
     */
    public XHLoadingView withBtnErrorText(String text) {
        this.btn_error_text = text;
        return this;
    }

    /**
     * 加載錯誤的文字提示
     * @param resId
     * @return
     */
    public XHLoadingView withLoadErrorText(int resId) {
        this.mLoadErrorText = getResources().getString(resId);
        return this;
    }
    public XHLoadingView withLoadErrorText(String mLoadedErrorText) {
        this.mLoadErrorText = mLoadedErrorText;
        return this;
    }

    /**
     * 加載無網絡的Button的文字提示
     * @param text
     * @return
     */
    public XHLoadingView withBtnNoNetText(String text) {
        this.btn_nonet_text = text;
        return this;
    }

    /**
     * 加載沒有網路的文字提示
     * @param mLoadedNoNetText
     * @return
     */
    public XHLoadingView withLoadNoNetworkText(String mLoadedNoNetText) {
        this.mLoadNoNetworkText = mLoadedNoNetText;
        return this;
    }

    public XHLoadingView withLoadingText(int resId) {
        this.mLoadingText = getResources().getString(resId);
        return this;
    }

    public XHLoadingView withLoadingText(String mLoadingText) {
        this.mLoadingText = mLoadingText;
        return this;
    }

}

針對不同的情況作了不同的處理,然后我們在需要的Activity調用。

    private XHLoadingView mLoadingView;
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display);
        mLoadingView = (XHLoadingView) findViewById(R.id.lv_loading);
        mLoadingView.withLoadEmptyText("≥﹏≤ , 啥也木有 !").withEmptyIcon(R.drawable.disk_file_no_data).withBtnEmptyEnnable(false)
                    .withErrorIco(R.drawable.ic_chat_empty).withLoadErrorText("(?( ˙??˙? )?)??????,我家程序猿跑路了 !").withBtnErrorText("臭狗屎!!!")
                    .withLoadNoNetworkText("你擋著信號啦o( ̄ヘ ̄o)??? 你走").withNoNetIcon(R.drawable.ic_chat_empty).withBtnNoNetText("網弄好了,重試")
                    .withLoadingIcon(R.drawable.loading_animation).withLoadingText("加載中...").withOnRetryListener(new XHLoadingView.OnRetryListener() {
                @Override
                public void onRetry() {
                    SnackbarUtil.show(mLoadingView,"已經在努力重試了",0);
                }
            }).build();
     }

........

  //加載中
      mLoadingView.setVisibility(View.VISIBLE);
      mLoadingView.setState(LoadingState.STATE_LOADING);

 //空數據
      mLoadingView.setVisibility(View.VISIBLE);
      mLoadingView.setState(LoadingState.STATE_EMPTY)
 //無網絡
      mLoadingView.setVisibility(View.VISIBLE);
      mLoadingView.setState(LoadingState.STATE_NO_NET);

 //加載錯誤
      mLoadingView.setVisibility(View.VISIBLE);
      mLoadingView.setState(LoadingState.STATE_ERROR);

.......


   }

源碼中注釋詳細,就不用再做過多的解釋了吧!

完整代碼XHLoadingView

作者:xuhao
QQ:504105930
轉載請注明出處:http://blog.csdn.net/u011974987/article/details/51455333
希望您能指出寶貴意見,謝謝。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,247評論 6 543
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,520評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 178,362評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,805評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,541評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,896評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,887評論 3 447
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,062評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,608評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,356評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,555評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,077評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,769評論 3 349
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,175評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,489評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,289評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,516評論 2 379

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,737評論 25 708
  • 問答題47 /72 常見瀏覽器兼容性問題與解決方案? 參考答案 (1)瀏覽器兼容問題一:不同瀏覽器的標簽默認的外補...
    _Yfling閱讀 13,781評論 1 92
  • 內容抽屜菜單ListViewWebViewSwitchButton按鈕點贊按鈕進度條TabLayout圖標下拉刷新...
    皇小弟閱讀 46,865評論 22 665
  • 【作者】喬冠清 【導師】劉艷 袁浩 鄭鵬 【導圖解說】這幅導圖主要說明了藏羚羊跪拜這篇課文的主要內容是一開始老獵人...
    喬丹2005閱讀 726評論 4 3
  • 面授,顧名思義,就是面對面的授課,主要就是集中在課堂里直接授課學習。相信大家對此并不陌生,九年義務教務就是這個模式...
    小范媽閱讀 2,021評論 0 1