Repository: hss01248/PageStateManager
Branch: master
Commit: 5ed8b4083e40
Files: 60
Total size: 97.8 KB
Directory structure:
gitextract_9l4znntb/
├── .gitignore
├── LICENSE
├── README.md
├── app/
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── hss01248/
│ │ └── pagestate/
│ │ └── demo/
│ │ └── ApplicationTest.java
│ ├── main/
│ │ ├── AndroidManifest.xml
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── hss01248/
│ │ │ └── pagestate/
│ │ │ └── demo/
│ │ │ ├── BaseActivity.java
│ │ │ ├── BaseApp.java
│ │ │ ├── CustomUIActy.java
│ │ │ ├── IRequestCallback.java
│ │ │ ├── LoadingView.java
│ │ │ ├── MainActivity.java
│ │ │ ├── ShapeLoadingView.java
│ │ │ ├── SplashActy.java
│ │ │ └── XmlActivity.java
│ │ └── res/
│ │ ├── attr/
│ │ │ └── loading_arrts.xml
│ │ ├── layout/
│ │ │ ├── activity_inxml.xml
│ │ │ ├── activity_main.xml
│ │ │ ├── acty_splash.xml
│ │ │ ├── base_activity.xml
│ │ │ ├── load_view.xml
│ │ │ ├── pager_empty_2.xml
│ │ │ ├── pager_error_2.xml
│ │ │ └── pager_loading_2.xml
│ │ └── values/
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test/
│ └── java/
│ └── com/
│ └── hss01248/
│ └── pagestate/
│ └── demo/
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── pagestate/
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── hss01248/
│ │ └── pagestate/
│ │ └── ApplicationTest.java
│ ├── main/
│ │ ├── AndroidManifest.xml
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── hss01248/
│ │ │ └── pagestate/
│ │ │ ├── IViewState.java
│ │ │ ├── NoNetworkHelper.java
│ │ │ ├── PageStateConfig.java
│ │ │ ├── PageStateManager.java
│ │ │ └── StatefulFrameLayout.java
│ │ └── res/
│ │ ├── drawable/
│ │ │ ├── loading_shadow.xml
│ │ │ ├── progressstyleshape.xml
│ │ │ └── selector_btn_bg.xml
│ │ ├── layout/
│ │ │ ├── pager_empty.xml
│ │ │ ├── pager_error.xml
│ │ │ └── pager_loading.xml
│ │ ├── values/
│ │ │ └── strings.xml
│ │ ├── values-in/
│ │ │ └── strings.xml
│ │ ├── values-ms/
│ │ │ └── strings.xml
│ │ ├── values-vi/
│ │ │ └── strings.xml
│ │ └── values-zh/
│ │ └── strings.xml
│ └── test/
│ └── java/
│ └── com/
│ └── hss01248/
│ └── pagestate/
│ └── ExampleUnitTest.java
└── settings.gradle
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Built application files
*.apk
*.ap_
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# Intellij
*.iml
.idea/workspace.xml
# Keystore files
*.jks
.idea/
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# PageStateManager/StatefulFrameLayout
页面状态管理
[](https://jitpack.io/#hss01248/PageStateManager)
在张鸿洋的[LoadingAndRetryManager](https://github.com/hongyangAndroid/LoadingAndRetryManager)的基础上改写,修正一些bug,优化api,并提供使用时封装的例子
# 特性
* api超级简单
* 可以在xml中使用StatefulFrameLayout
* 也可以不改动xml,直接在代码里使用PageStateManager
* 错误页面和空白页面均提供了点击事件的回调,直接实现即可
* 不改动framlayout本身任何属性,依然可以添加多个子view
# 更新:fragment的操作改变了
由于fragment的生命周期引起的bug,已取消原先直接传入fragment对象的方式.
请改成传入组成fragment的view,注意该view对象传入时,其parent不能为空,也就是,该view不能是xml的根view,可以自己随便包一层.
ps.
其实fragment本质也是基于view包裹了一层api,搞点生命周期之类的,api难用得要死,还一大堆坑,还不如自己包装一个view,自己加点生命周期,高度可控,减少bug.我的项目中从来都不用fragment,都是自己把view包装成各种page.
# API
> 参考demo里的,自己封装一层(拷过去改一改)
## 接口
```
public interface IViewState {
void showLoading();
void showError(CharSequence msg);
void showContent();
void showEmpty();
}
```
# 四个级别的配置
### 库内默认
自带Loading,Empty,Error的xml:
```
public static int BASE_LOADING_LAYOUT_ID = R.layout.pager_loading;
public static int BASE_RETRY_LAYOUT_ID = R.layout.pager_error;
public static int BASE_EMPTY_LAYOUT_ID = R.layout.pager_empty;
```
## 使用时可全局配置
在application的oncreate里调用:
也就是修改上述的三个静态变量:
```
PageStateManager.initInAppOnCreate():
```
```
public static void initInApp(int layoutIdOfEmpty, int layoutIdOfLoading, int layoutIdOfError) {
if (layoutIdOfEmpty != 0) {
BASE_EMPTY_LAYOUT_ID = layoutIdOfEmpty;
}
if (layoutIdOfLoading != 0) {
BASE_LOADING_LAYOUT_ID = layoutIdOfLoading;
}
if (layoutIdOfError != 0) {
BASE_RETRY_LAYOUT_ID = layoutIdOfError;
}
}
```
## 单个页面的配置:
### 可配置的项目:
// PageConfig为抽象类:
仅一个必须实现的方法:
public abstract class PageConfig {
public abstract void onRetry(View retryView);//必须实现
public void onEmtptyViewClicked(View emptyView) {
onRetry(emptyView);
}
public boolean isFirstStateLoading(){
return true;
}
public String emptyMsg(){
return "";
}
public int customLoadingLayoutId() {
return PageStateManager.BASE_LOADING_LAYOUT_ID;
}
public int customErrorLayoutId() {
return PageStateManager.BASE_RETRY_LAYOUT_ID;
}
public int customEmptyLayoutId() {
return PageStateManager.BASE_EMPTY_LAYOUT_ID;
}
### xml里使用statefulFrameLayout时:
```
```
```
statefulFrameLayout.init(new PageConfig() {
@Override
public void onRetry(View retryView) {
doNet();
}
});
```
### 或者使用PageStateManager:
```
/**
*
* @param container 必须为activity或者view.如果是view,则该view对象必须有parent
*/
pageStateManager = PageStateManager.initWhenUse(container,new MyPageConfig() {
@Override
protected void onReallyRetry() {
doNet();
}
@Override
public int customEmptyLayoutId() {
return R.layout.pager_empty_2;
}
@Override
public int customLoadingLayoutId() {
return R.layout.pager_loading_2;
}
@Override
public int customErrorLayoutId() {
return R.layout.pager_error_2;
}
});
```
## 控制页面状态的api:
```
public void showLoading()
public void showContent()
public void showEmpty()
public void showError(CharSequence errorMsg)
```
# demo中的默认的几个页面状态UI图



其中无网络时弹出dialog:

无网络的对话框可以全局复写:
```
NoNetworkHelper.setShowDialogImpl(IShowDialog showDialog)
public interface IShowDialog{
void showNoNetWorkDlg(final Context context);
}
```
# 使用
## gradle
**Step 1.** Add the JitPack repository to your build file
Add it in your root build.gradle at the end of repositories:
```
allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}
}
```
**Step 2.** Add the dependency
```
dependencies {
compile 'com.github.hss01248:PageStateManager:3.0.1'
}
```
## 示例代码(详见demo)
## xml里不写StatefulFramelayout时:
```
private void initView() {
setContentView(R.layout.activity_main);
pageStateManager = PageStateManager.initWhenUse(this,new PageConfig() {
@Override
public int customEmptyLayoutId() {
return R.layout.pager_empty_2;
}
@Override
public void onRetry(View retryView) {
doNet();
}
@Override
public int customLoadingLayoutId() {
return R.layout.pager_loading_2;
}
@Override
public int customErrorLayoutId() {
return R.layout.pager_error_2;
}
});
}
private void doNet() {
pageStateManager.showLoading();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
int state = new Random().nextInt(3);
switch (state){
case 0:
pageStateManager.showError("稍候重试");
break;
case 1:
pageStateManager.showEmpty();
break;
case 2:
pageStateManager.showContent();
}
}
},2000);
}
```
## 在xml里直接写时:
```
......
statefulFrameLayout = (StatefulFrameLayout)findViewById(R.id.pager);
statefulFrameLayout.init(new PageConfig() {
@Override
public void onRetry(View retryView) {
doNet();
}
});
doNet();
}
private void doNet() {
statefulFrameLayout.showLoading();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
int state = new Random().nextInt(3);
switch (state){
case 0:
statefulFrameLayout.showError("稍候重试222222");
break;
case 1:
statefulFrameLayout.showEmpty();
break;
case 2:
statefulFrameLayout.showContent();
}
}
},2000);
}
```
# 注意事项
1.给view对象设置状态时,该对象必须有parent
2.
# blog
[介绍一下页面状态管理类PageStateManager,我实在看不下去你们直接用Layout](http://www.jianshu.com/p/665a69e9436b)
================================================
FILE: app/.gitignore
================================================
/build
================================================
FILE: app/build.gradle
================================================
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.hss01248.pagestate.demo"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'androidx.appcompat:appcompat:1.1.0'
compile project(path: ':pagestate')
compile 'com.nineoldandroids:library:2.4.0'
//compile 'com.jakewharton:butterknife:10.2.1'
//annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.1'
//compile 'com.wuhenzhizao:titlebar:1.2.0'
}
================================================
FILE: app/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in I:\dev\Android\sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
================================================
FILE: app/src/androidTest/java/com/hss01248/pagestate/demo/ApplicationTest.java
================================================
package com.hss01248.pagestate.demo;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* Testing Fundamentals
*/
public class ApplicationTest extends ApplicationTestCase {
public ApplicationTest() {
super(Application.class);
}
}
================================================
FILE: app/src/main/AndroidManifest.xml
================================================
================================================
FILE: app/src/main/java/com/hss01248/pagestate/demo/BaseActivity.java
================================================
package com.hss01248.pagestate.demo;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.hss01248.pagestate.PageStateConfig;
import com.hss01248.pagestate.PageStateManager;
/**
* time:2020/4/26
* author:hss
* desription:
*/
public class BaseActivity extends AppCompatActivity {
BaseConfig config;
TextView titlebar;
LinearLayout linearLayout;
PageStateManager stateManager;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_activity);
linearLayout = (LinearLayout) findViewById(R.id.ll_root);
titlebar = (TextView) findViewById(R.id.titlebar);
config = new BaseConfig();
configPage(config);
applyConfig(config);
}
protected void requestData(IRequestCallback callback){
}
private void applyConfig(BaseConfig config) {
if(config.hasPageStatus ){
stateManager = PageStateManager.initWhenUse(linearLayout, new PageStateConfig() {
@Override
public void onRetry(View retryView) {
stateManager.showLoading();
doNet();
}
});
doNet();
}
}
private void doNet() {
requestData(new IRequestCallback() {
@Override
public void onSuccess() {
stateManager.showContent();
}
@Override
public void onError(String msg) {
stateManager.showError(msg);
}
@Override
public void onEmpty() {
stateManager.showEmpty();
}
});
}
protected void configPage(BaseConfig config) {
config.hasPageStatus = true;
}
public static class BaseConfig{
boolean hasPageStatus = true;
boolean hasTitlebar = true;
PageStateConfig stateConfig;
}
}
================================================
FILE: app/src/main/java/com/hss01248/pagestate/demo/BaseApp.java
================================================
package com.hss01248.pagestate.demo;
import android.app.Application;
import com.hss01248.pagestate.PageStateManager;
/**
* Created by huangshuisheng on 2017/10/16.
*/
public class BaseApp extends Application {
@Override
public void onCreate() {
super.onCreate();
PageStateManager.initInAppOnCreate(R.layout.pager_empty,R.layout.pager_loading,R.layout.pager_error);
}
}
================================================
FILE: app/src/main/java/com/hss01248/pagestate/demo/CustomUIActy.java
================================================
package com.hss01248.pagestate.demo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import android.view.View;
import com.hss01248.pagestate.PageStateConfig;
import com.hss01248.pagestate.PageStateManager;
import java.util.Random;
/**
* Created by huangshuisheng on 2017/10/16.
*/
public class CustomUIActy extends Activity {
PageStateManager pageStateManager;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
doNet();
}
private void initView() {
setContentView(R.layout.activity_main);
pageStateManager = PageStateManager.initWhenUse(this,new PageStateConfig() {
@Override
public int customEmptyLayoutId() {
return R.layout.pager_empty_2;
}
@Override
public void onRetry(View retryView) {
doNet();
}
@Override
public int customLoadingLayoutId() {
return R.layout.pager_loading_2;
}
@Override
public int customErrorLayoutId() {
return R.layout.pager_error_2;
}
});
}
private void doNet() {
pageStateManager.showLoading();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
int state = new Random().nextInt(3);
switch (state){
case 0:
pageStateManager.showError("稍候重试");
break;
case 1:
pageStateManager.showEmpty();
break;
case 2:
pageStateManager.showContent();
}
}
},2000);
}
}
================================================
FILE: app/src/main/java/com/hss01248/pagestate/demo/IRequestCallback.java
================================================
package com.hss01248.pagestate.demo;
/**
* time:2020/4/26
* author:hss
* desription:
*/
public interface IRequestCallback {
void onSuccess();
void onError(String msg);
void onEmpty();
}
================================================
FILE: app/src/main/java/com/hss01248/pagestate/demo/LoadingView.java
================================================
package com.hss01248.pagestate.demo;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
/**
* Created by cy on 5/24/16.
*
* 功能描述:
*/
public class LoadingView extends FrameLayout {
private static final int ANIMATION_DURATION = 500;
private static float mDistance = 200;
private ShapeLoadingView mShapeLoadingView;
private ImageView mIndicationIm;
private TextView mLoadTextView;
private int mTextAppearance;
private String mLoadText;
private boolean mLoading = false;
public LoadingView(Context context) {
super(context);
}
public LoadingView(Context context, AttributeSet attrs) {
super(context, attrs, 0);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray typedArray = context
.obtainStyledAttributes(attrs, R.styleable.LoadingView);
mLoadText = typedArray.getString(R.styleable.LoadingView_loadingText);
mTextAppearance = typedArray.getResourceId(R.styleable.LoadingView_loadingTextAppearance, -1);
typedArray.recycle();
}
public LoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public LoadingView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs);
}
public int dip2px(float dipValue) {
final float scale = getContext().getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
View view = LayoutInflater.from(getContext()).inflate(R.layout.load_view, null);
mDistance = dip2px(54f);
LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER;
mShapeLoadingView = (ShapeLoadingView) view.findViewById(R.id.shapeLoadingView);
mIndicationIm = (ImageView) view.findViewById(R.id.indication);
mLoadTextView = (TextView) view.findViewById(R.id.promptTV);
if (mTextAppearance != -1) {
mLoadTextView.setTextAppearance(getContext(), mTextAppearance);
}
setLoadingText(mLoadText);
addView(view, layoutParams);
// startLoading(900);
}
private AnimatorSet mAnimatorSetThrowUp = null, mAnimatorSetFallDown = null;
private Runnable mFreeFallRunnable = new Runnable() {
@Override
public void run() {
fallDown();
}
};
private void startLoading(long delay) {
if (mAnimatorSetThrowUp != null && mAnimatorSetThrowUp.isRunning()) {
return;
}
if (mAnimatorSetFallDown != null && mAnimatorSetFallDown.isRunning()) {
return;
}
this.removeCallbacks(mFreeFallRunnable);
mLoading = true;
if (delay > 0) {
this.postDelayed(mFreeFallRunnable, delay);
} else {
this.post(mFreeFallRunnable);
}
}
private void stopLoading() {
if (mAnimatorSetThrowUp != null) {
if (mAnimatorSetThrowUp.isRunning()) {
mAnimatorSetThrowUp.cancel();
}
mAnimatorSetThrowUp = null;
}
if (mAnimatorSetFallDown != null) {
if (mAnimatorSetFallDown.isRunning()) {
mAnimatorSetFallDown.cancel();
}
mAnimatorSetFallDown = null;
}
mLoading = false;
this.removeCallbacks(mFreeFallRunnable);
}
@Override
public void setVisibility(int visibility) {
super.setVisibility(visibility);
if (visibility == View.VISIBLE) {
startLoading(200);
} else {
stopLoading();
}
}
public void setLoadingText(CharSequence loadingText) {
if (TextUtils.isEmpty(loadingText)) {
mLoadTextView.setVisibility(GONE);
} else {
mLoadTextView.setVisibility(VISIBLE);
}
mLoadTextView.setText(loadingText);
}
/**
* 上抛
*/
public void throwUp() {
if (!mLoading)
return;
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mShapeLoadingView, "translationY", mDistance, 0);
ObjectAnimator scaleIndication = ObjectAnimator.ofFloat(mIndicationIm, "scaleX", 0.2f, 1);
ObjectAnimator objectAnimator1 = null;
switch (mShapeLoadingView.getShape()) {
case SHAPE_RECT:
objectAnimator1 = ObjectAnimator.ofFloat(mShapeLoadingView, "rotation", 0, -120);
break;
case SHAPE_CIRCLE:
objectAnimator1 = ObjectAnimator.ofFloat(mShapeLoadingView, "rotation", 0, 180);
break;
case SHAPE_TRIANGLE:
objectAnimator1 = ObjectAnimator.ofFloat(mShapeLoadingView, "rotation", 0, 180);
break;
}
objectAnimator.setDuration(ANIMATION_DURATION);
objectAnimator1.setDuration(ANIMATION_DURATION);
objectAnimator.setInterpolator(new DecelerateInterpolator(factor));
objectAnimator1.setInterpolator(new DecelerateInterpolator(factor));
mAnimatorSetThrowUp = new AnimatorSet();
mAnimatorSetThrowUp.setDuration(ANIMATION_DURATION);
mAnimatorSetThrowUp.playTogether(objectAnimator, objectAnimator1, scaleIndication);
mAnimatorSetThrowUp.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
if (mLoading) {
fallDown();
}
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
mAnimatorSetThrowUp.start();
}
public float factor = 1.2f;
/**
* 下落
*/
public void fallDown() {
if (!mLoading)
return;
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mShapeLoadingView, "translationY", 0, mDistance);
ObjectAnimator scaleIndication = ObjectAnimator.ofFloat(mIndicationIm, "scaleX", 1, 0.2f);
objectAnimator.setDuration(ANIMATION_DURATION);
objectAnimator.setInterpolator(new AccelerateInterpolator(factor));
mAnimatorSetFallDown = new AnimatorSet();
mAnimatorSetFallDown.setDuration(ANIMATION_DURATION);
mAnimatorSetFallDown.playTogether(objectAnimator, scaleIndication);
mAnimatorSetFallDown.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
if (mLoading) {
mShapeLoadingView.changeShape();
throwUp();
}
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
mAnimatorSetFallDown.start();
}
}
================================================
FILE: app/src/main/java/com/hss01248/pagestate/demo/MainActivity.java
================================================
package com.hss01248.pagestate.demo;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import com.hss01248.pagestate.PageStateConfig;
import com.hss01248.pagestate.PageStateManager;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
PageStateManager pageStateManager;
Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
pageStateManager = PageStateManager.initWhenUse(this, new PageStateConfig() {
@Override
public String emptyMsg() {
return "自定义的空msg\n你可以点击重试一下";
}
@Override
public void onRetry(View retryView) {
doNet();
}
@Override
public void onEmtptyViewClicked(View emptyView) {
super.onEmtptyViewClicked(emptyView);
doNet();
}
@Override
public boolean darkMode() {
return true;
}
@Override
public boolean isFirstStateLoading() {
return false;
}
});
doNet();
}
@Override
protected void onResume() {
super.onResume();
// doNet();
}
private void doNet() {
pageStateManager.showLoading(50);
handler.postDelayed(new Runnable() {
@Override
public void run() {
int state = new Random().nextInt(3);
switch (state){
case 0:
pageStateManager.showError("error occured!!!!!!!!!!!!");
break;
case 1:
pageStateManager.showEmpty();
break;
case 2:
pageStateManager.showContent();
}
}
},2000);
}
}
================================================
FILE: app/src/main/java/com/hss01248/pagestate/demo/ShapeLoadingView.java
================================================
package com.hss01248.pagestate.demo;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Build;
import androidx.core.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import com.nineoldandroids.animation.ArgbEvaluator;
/**
* Created by cy on 5/24/16.
*
* 功能描述:
*/
public class ShapeLoadingView extends View {
private static final float genhao3 = 1.7320508075689f;
private static final float mTriangle2Circle = 0.25555555f;
private Context mContext;
private Shape mShape = Shape.SHAPE_CIRCLE;
private Interpolator mInterpolator = new DecelerateInterpolator();
private ArgbEvaluator mArgbEvaluator = new ArgbEvaluator();
private int mTriangleColor;
private int mCircleColor;
private int mRectColor;
/**
* 用赛贝尔曲线画圆
*/
private float mMagicNumber = 0.55228475f;
public ShapeLoadingView(Context context) {
super(context);
this.mContext = context;
init();
}
public ShapeLoadingView(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
init();
}
public ShapeLoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext = context;
init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ShapeLoadingView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
this.mContext = context;
init();
}
private void init() {
mPaint = new Paint();
mPaint.setColor(ContextCompat.getColor(mContext, R.color.triangle));
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
setBackgroundColor(ContextCompat.getColor(mContext, R.color.view_bg));
mTriangleColor = ContextCompat.getColor(mContext, R.color.triangle);
mCircleColor = ContextCompat.getColor(mContext, R.color.circle);
mRectColor = ContextCompat.getColor(mContext, R.color.triangle);
}
public boolean mIsLoading = false;
private Paint mPaint;
private float mControlX = 0;
private float mControlY = 0;
private float mAnimPercent;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (getVisibility() == GONE) {
return;
}
// FIXME: 15/6/15 动画待优化
switch (mShape) {
case SHAPE_TRIANGLE:
if (mIsLoading) {
mAnimPercent += 0.1611113;
int color = (int) mArgbEvaluator.evaluate(mAnimPercent, mTriangleColor, mCircleColor);
mPaint.setColor(color);
// triangle to circle
Path path = new Path();
path.moveTo(relativeXFromView(0.5f), relativeYFromView(0f));
if (mAnimPercent >= 1) {
mShape = Shape.SHAPE_CIRCLE;
mIsLoading = false;
mAnimPercent = 1;
}
float controlX = mControlX - relativeXFromView(mAnimPercent * mTriangle2Circle)
* genhao3;
float controlY = mControlY - relativeYFromView(mAnimPercent * mTriangle2Circle);
path.quadTo(relativeXFromView(1) - controlX, controlY, relativeXFromView(0.5f + genhao3 / 4), relativeYFromView(0.75f));
path.quadTo(relativeXFromView(0.5f), relativeYFromView(0.75f + 2 * mAnimPercent * mTriangle2Circle), relativeXFromView(0.5f - genhao3 / 4), relativeYFromView(0.75f));
path.quadTo(controlX, controlY, relativeXFromView(0.5f), relativeYFromView(0f));
path.close();
canvas.drawPath(path, mPaint);
invalidate();
} else {
Path path = new Path();
mPaint.setColor(ContextCompat.getColor(mContext, R.color.triangle));
path.moveTo(relativeXFromView(0.5f), relativeYFromView(0f));
path.lineTo(relativeXFromView(1), relativeYFromView(genhao3 / 2f));
path.lineTo(relativeXFromView(0), relativeYFromView(genhao3 / 2f));
mControlX = relativeXFromView(0.5f - genhao3 / 8.0f);
mControlY = relativeYFromView(3 / 8.0f);
mAnimPercent = 0;
path.close();
canvas.drawPath(path, mPaint);
}
break;
case SHAPE_CIRCLE:
if (mIsLoading) {
float magicNumber = mMagicNumber + mAnimPercent;
mAnimPercent += 0.12;
if (magicNumber + mAnimPercent >= 1.9f) {
mShape = Shape.SHAPE_RECT;
mIsLoading = false;
}
int color = (int) mArgbEvaluator.evaluate(mAnimPercent, mCircleColor, mRectColor);
mPaint.setColor(color);
Path path = new Path();
path.moveTo(relativeXFromView(0.5f), relativeYFromView(0f));
path.cubicTo(relativeXFromView(0.5f + magicNumber / 2), relativeYFromView(0f),
relativeXFromView(1), relativeYFromView(0.5f - magicNumber / 2),
relativeXFromView(1f), relativeYFromView(0.5f));
path.cubicTo(
relativeXFromView(1), relativeXFromView(0.5f + magicNumber / 2),
relativeXFromView(0.5f + magicNumber / 2), relativeYFromView(1f),
relativeXFromView(0.5f), relativeYFromView(1f));
path.cubicTo(relativeXFromView(0.5f - magicNumber / 2), relativeXFromView(1f),
relativeXFromView(0), relativeYFromView(0.5f + magicNumber / 2),
relativeXFromView(0f), relativeYFromView(0.5f));
path.cubicTo(relativeXFromView(0f), relativeXFromView(0.5f - magicNumber / 2),
relativeXFromView(0.5f - magicNumber / 2), relativeYFromView(0),
relativeXFromView(0.5f), relativeYFromView(0f));
path.close();
canvas.drawPath(path, mPaint);
invalidate();
} else {
mPaint.setColor(ContextCompat.getColor(mContext, R.color.circle));
Path path = new Path();
float magicNumber = mMagicNumber;
path.moveTo(relativeXFromView(0.5f), relativeYFromView(0f));
path.cubicTo(relativeXFromView(0.5f + magicNumber / 2), 0,
relativeXFromView(1), relativeYFromView(magicNumber / 2),
relativeXFromView(1f), relativeYFromView(0.5f));
path.cubicTo(
relativeXFromView(1), relativeXFromView(0.5f + magicNumber / 2),
relativeXFromView(0.5f + magicNumber / 2), relativeYFromView(1f),
relativeXFromView(0.5f), relativeYFromView(1f));
path.cubicTo(relativeXFromView(0.5f - magicNumber / 2), relativeXFromView(1f),
relativeXFromView(0), relativeYFromView(0.5f + magicNumber / 2),
relativeXFromView(0f), relativeYFromView(0.5f));
path.cubicTo(relativeXFromView(0f), relativeXFromView(0.5f - magicNumber / 2),
relativeXFromView(0.5f - magicNumber / 2), relativeYFromView(0),
relativeXFromView(0.5f), relativeYFromView(0f));
mAnimPercent = 0;
path.close();
canvas.drawPath(path, mPaint);
}
break;
case SHAPE_RECT:
if (mIsLoading) {
mAnimPercent += 0.15;
if (mAnimPercent >= 1) {
mShape = Shape.SHAPE_TRIANGLE;
mIsLoading = false;
mAnimPercent = 1;
}
int color = (int) mArgbEvaluator.evaluate(mAnimPercent, mRectColor, mTriangleColor);
mPaint.setColor(color);
Path path = new Path();
path.moveTo(relativeXFromView(0.5f * mAnimPercent), 0);
path.lineTo(relativeYFromView(1 - 0.5f * mAnimPercent), 0);
float distanceX = (mControlX) * mAnimPercent;
float distanceY = (relativeYFromView(1f) - mControlY) * mAnimPercent;
path.lineTo(relativeXFromView(1f) - distanceX, relativeYFromView(1f) - distanceY);
path.lineTo(relativeXFromView(0f) + distanceX, relativeYFromView(1f) - distanceY);
path.close();
canvas.drawPath(path, mPaint);
invalidate();
} else {
mPaint.setColor(ContextCompat.getColor(mContext, R.color.rect));
mControlX = relativeXFromView(0.5f - genhao3 / 4);
mControlY = relativeYFromView(0.75f);
Path path = new Path();
path.moveTo(relativeXFromView(0f), relativeYFromView(0f));
path.lineTo(relativeXFromView(1f), relativeYFromView(0f));
path.lineTo(relativeXFromView(1f), relativeYFromView(1f));
path.lineTo(relativeXFromView(0f), relativeYFromView(1f));
path.close();
mAnimPercent = 0;
canvas.drawPath(path, mPaint);
}
break;
}
}
private float relativeXFromView(float percent) {
return getWidth() * percent;
}
private float relativeYFromView(float percent) {
return getHeight() * percent;
}
public void changeShape() {
mIsLoading = true;
invalidate();
}
public enum Shape {
SHAPE_TRIANGLE, SHAPE_RECT, SHAPE_CIRCLE
}
@Override
public void setVisibility(int visibility) {
super.setVisibility(visibility);
if (visibility == VISIBLE) {
invalidate();
}
}
public Shape getShape() {
return mShape;
}
}
================================================
FILE: app/src/main/java/com/hss01248/pagestate/demo/SplashActy.java
================================================
package com.hss01248.pagestate.demo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.view.View;
import android.widget.Button;
/**
* Created by huangshuisheng on 2017/10/16.
*/
public class SplashActy extends Activity implements View.OnClickListener {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acty_splash);
findViewById(R.id.button).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button:
startActivity(new Intent(this,MainActivity.class));
break;
case R.id.button2:
startActivity(new Intent(this,CustomUIActy.class));
break;
case R.id.button3:
startActivity(new Intent(this,XmlActivity.class));
break;
}
}
}
================================================
FILE: app/src/main/java/com/hss01248/pagestate/demo/XmlActivity.java
================================================
package com.hss01248.pagestate.demo;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import com.hss01248.pagestate.PageStateConfig;
import com.hss01248.pagestate.StatefulFrameLayout;
import java.util.Random;
/**
* time:2020/4/25
* author:hss
* desription:
*/
public class XmlActivity extends AppCompatActivity {
StatefulFrameLayout statefulFrameLayout;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inxml);
statefulFrameLayout = (StatefulFrameLayout)findViewById(R.id.pager);
statefulFrameLayout.init(new PageStateConfig() {
@Override
public void onRetry(View retryView) {
doNet();
}
});
doNet();
}
private void doNet() {
statefulFrameLayout.showLoading();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
int state = new Random().nextInt(3);
switch (state){
case 0:
statefulFrameLayout.showError("稍候重试222222");
break;
case 1:
statefulFrameLayout.showEmpty();
break;
case 2:
statefulFrameLayout.showContent();
}
}
},2000);
}
}
================================================
FILE: app/src/main/res/attr/loading_arrts.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_inxml.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_main.xml
================================================
================================================
FILE: app/src/main/res/layout/acty_splash.xml
================================================
================================================
FILE: app/src/main/res/layout/base_activity.xml
================================================
================================================
FILE: app/src/main/res/layout/load_view.xml
================================================
================================================
FILE: app/src/main/res/layout/pager_empty_2.xml
================================================
================================================
FILE: app/src/main/res/layout/pager_error_2.xml
================================================
================================================
FILE: app/src/main/res/layout/pager_loading_2.xml
================================================
================================================
FILE: app/src/main/res/values/colors.xml
================================================
#3F51B5#303F9F#FF4081#fad0d1#e62117#eb686c#00000000#25808080#f5f5f5
================================================
FILE: app/src/main/res/values/dimens.xml
================================================
16dp16dp
================================================
FILE: app/src/main/res/values/strings.xml
================================================
PageStateManager
================================================
FILE: app/src/main/res/values/styles.xml
================================================
================================================
FILE: app/src/test/java/com/hss01248/pagestate/demo/ExampleUnitTest.java
================================================
package com.hss01248.pagestate.demo;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
================================================
FILE: build.gradle
================================================
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Sun Apr 26 13:04:21 CST 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
android.enableJetifier=true
android.useAndroidX=true
================================================
FILE: gradlew
================================================
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: pagestate/.gitignore
================================================
/build
================================================
FILE: pagestate/build.gradle
================================================
apply plugin: 'com.android.library'
android {
compileSdkVersion 28
defaultConfig {
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
api 'androidx.appcompat:appcompat:1.1.0'
}
================================================
FILE: pagestate/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in I:\dev\Android\sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
================================================
FILE: pagestate/src/androidTest/java/com/hss01248/pagestate/ApplicationTest.java
================================================
package com.hss01248.pagestate;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* Testing Fundamentals
*/
public class ApplicationTest extends ApplicationTestCase {
public ApplicationTest() {
super(Application.class);
}
}
================================================
FILE: pagestate/src/main/AndroidManifest.xml
================================================
================================================
FILE: pagestate/src/main/java/com/hss01248/pagestate/IViewState.java
================================================
package com.hss01248.pagestate;
/**
* time:2020/4/25
* author:hss
* desription:
*/
public interface IViewState {
void showLoading();
default void showLoading(int progress){
showLoading();
}
void showError(CharSequence msg);
void showContent();
void showEmpty();
}
================================================
FILE: pagestate/src/main/java/com/hss01248/pagestate/NoNetworkHelper.java
================================================
package com.hss01248.pagestate;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import androidx.appcompat.app.AlertDialog;
/**
* time:2020/4/25
* author:hss
* desription:
*/
public class NoNetworkHelper {
public static void setShowDialogImpl(IShowDialog showDialog) {
NoNetworkHelper.showDialog = showDialog;
}
static IShowDialog showDialog;
public interface IShowDialog{
void showNoNetWorkDlg(final Context context);
}
static void showNoNetWorkDlg(final Context context) {
if(showDialog != null){
showDialog.showNoNetWorkDlg(context);
return;
}
AlertDialog dialog = null;
try {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
dialog = builder
.setTitle(R.string.pagestate_no_network_title)
.setMessage(R.string.pagestate_no_network_msg).setPositiveButton(R.string.pagestate_go_setting, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 跳转到系统的网络设置界面
Intent intent = null;
// 先判断当前系统版本
if(android.os.Build.VERSION.SDK_INT > 10){ // 3.0以上
//intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
}else{
intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings");
}
context.startActivity(intent);
dialog.dismiss();
}
}).setNegativeButton(R.string.pagestate_cancel, null)
.show();
}catch (Exception e){
e.printStackTrace();
}
}
static boolean isNetWorkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) {
return false;
} else {
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info == null) {
return false;
} else {
if (info.isAvailable()) {
return true;
}
}
}
return false;
}
}
================================================
FILE: pagestate/src/main/java/com/hss01248/pagestate/PageStateConfig.java
================================================
package com.hss01248.pagestate;
import android.view.View;
public abstract class PageStateConfig {
public abstract void onRetry(View retryView);
public void onEmtptyViewClicked(View emptyView) {
onRetry(emptyView);
}
public boolean isFirstStateLoading(){
return true;
}
public String emptyMsg(){
return "";
}
public boolean darkMode(){
return PageStateManager.isDarkMode;
}
public int customLoadingLayoutId() {
return PageStateManager.BASE_LOADING_LAYOUT_ID;
}
public int customErrorLayoutId() {
return PageStateManager.BASE_RETRY_LAYOUT_ID;
}
public int customEmptyLayoutId() {
return PageStateManager.BASE_EMPTY_LAYOUT_ID;
}
public boolean showProgress(View emptyView,int progress){
return false;
}
}
================================================
FILE: pagestate/src/main/java/com/hss01248/pagestate/PageStateManager.java
================================================
package com.hss01248.pagestate;
import android.app.Activity;
import android.content.Context;
import androidx.fragment.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by zhy on 15/8/27.
*/
public class PageStateManager implements IViewState{
static int BASE_LOADING_LAYOUT_ID = R.layout.pager_loading;
static int BASE_RETRY_LAYOUT_ID = R.layout.pager_error;
static int BASE_EMPTY_LAYOUT_ID = R.layout.pager_empty;
public static void setGlobalDarkMode(boolean isDarkMode) {
PageStateManager.isDarkMode = isDarkMode;
}
static boolean isDarkMode = false;
public StatefulFrameLayout getStatefulLayout() {
return mLoadingAndRetryLayout;
}
StatefulFrameLayout mLoadingAndRetryLayout;
PageStateConfig pageListener = new PageStateConfig() {
@Override
public void onRetry(View retryView) {
}
};
PageStateManager(Context context){
}
private PageStateManager(Object activityOrView, PageStateConfig listener) {
ViewGroup contentParent = null;
Context context;
if (activityOrView instanceof Activity) {
Activity activity = (Activity) activityOrView;
context = activity;
contentParent = (ViewGroup) activity.findViewById(android.R.id.content);
} else if (activityOrView instanceof Fragment) {
Fragment fragment = (Fragment) activityOrView;
context = fragment.getActivity();
contentParent = (ViewGroup) (fragment.getView().getParent());
if (contentParent == null) {
throw new IllegalArgumentException("the fragment must already has a parent ,please do not invoke this in oncreateView,you should use this method in onActivityCreated() or onstart");
}
//throw new IllegalArgumentException("the support for fragment has been canceled,please use give me a view object which has a parent");
} else if (activityOrView instanceof View) {
View view = (View) activityOrView;
contentParent = (ViewGroup) (view.getParent());
if (contentParent == null) {
throw new IllegalArgumentException("the view must already has a parent ");
}
context = view.getContext();
} else {
throw new IllegalArgumentException("the container's type must be Fragment or Activity or a view ");
}
int childCount = contentParent.getChildCount();
//get contentParent
int index = 0;
View oldContent;
if (activityOrView instanceof View) {
oldContent = (View) activityOrView;
for (int i = 0; i < childCount; i++) {
if (contentParent.getChildAt(i) == oldContent) {
index = i;
break;
}
}
} else {
oldContent = contentParent.getChildAt(0);
}
contentParent.removeView(oldContent);
//setup content layout
StatefulFrameLayout statefulFrameLayout = new StatefulFrameLayout(context);
statefulFrameLayout.manager = this;
if(listener != null){
this.pageListener = listener;
}
ViewGroup.LayoutParams lp = oldContent.getLayoutParams();
contentParent.addView(statefulFrameLayout, index, lp);
statefulFrameLayout.setContentView(oldContent);
// setup loading,retry,empty layout
//setupLoadingLayout(listener, pageLayout);
// setupRetryLayout(listener, pageLayout);
//setupEmptyLayout(listener, pageLayout);
//callback
/* listener.onRetry(pageLayout.getRetryView());
listener.setLoadingEvent(pageLayout.getLoadingView());
listener.setEmptyEvent(pageLayout.getEmptyView());*/
mLoadingAndRetryLayout = statefulFrameLayout;
//初始状态:loading进去
if (pageListener.isFirstStateLoading()) {
mLoadingAndRetryLayout.showLoading();
} else {
mLoadingAndRetryLayout.showContent();
}
}
/**
* @param layoutIdOfEmpty
* @param layoutIdOfLoading
* @param layoutIdOfError
*/
public static void initInAppOnCreate(int layoutIdOfEmpty, int layoutIdOfLoading, int layoutIdOfError) {
if (layoutIdOfEmpty != 0) {
BASE_EMPTY_LAYOUT_ID = layoutIdOfEmpty;
}
if (layoutIdOfLoading != 0) {
BASE_LOADING_LAYOUT_ID = layoutIdOfLoading;
}
if (layoutIdOfError != 0) {
BASE_RETRY_LAYOUT_ID = layoutIdOfError;
}
}
public static PageStateManager initWhenUse(Object activityOrView, PageStateConfig listener) {
return new PageStateManager(activityOrView, listener);
}
@Override
public void showLoading() {
mLoadingAndRetryLayout.showLoading();
}
@Override
public void showLoading(int progress) {
mLoadingAndRetryLayout.showLoading(progress);
}
@Override
public void showError(CharSequence msg) {
mLoadingAndRetryLayout.showError(msg);
}
@Override
public void showContent() {
mLoadingAndRetryLayout.showContent();
}
@Override
public void showEmpty() {
mLoadingAndRetryLayout.showEmpty();
}
}
================================================
FILE: pagestate/src/main/java/com/hss01248/pagestate/StatefulFrameLayout.java
================================================
package com.hss01248.pagestate;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Looper;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by zhy on 15/8/26.
*/
public class StatefulFrameLayout extends FrameLayout implements IViewState {
public static final int STATUS_LOADING = 1;
public static final int STATUS_CONTENT = 2;
public static final int STATUS_EMPTY = 3;
public static final int STATUS_ERROR = 4;
private static final String TAG = StatefulFrameLayout.class.getSimpleName();
int status;
private View mLoadingView;
private View mRetryView;
private List contentViews = new ArrayList<>();
private View mEmptyView;
private LayoutInflater mInflater;
PageStateManager manager;
public StatefulFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mInflater = LayoutInflater.from(context);
initView(context, attrs, defStyleAttr);
}
public StatefulFrameLayout(Context context, AttributeSet attrs) {
this(context, attrs, -1);
}
public StatefulFrameLayout(Context context) {
this(context, null);
}
public void init(PageStateConfig listener){
manager.pageListener = listener;
}
private void initView(Context context, AttributeSet attrs, int defStyleAttr) {
int childCount = this.getChildCount();
if (childCount > 1) {
throw new RuntimeException("content must be one");
}
//xml里的布局是在这个layout初始化完成后才加入的
manager = new PageStateManager(context);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if(manager.pageListener.isFirstStateLoading()){
showLoading();
}
}
private boolean isMainThread() {
return Looper.myLooper() == Looper.getMainLooper();
}
@Override
public void showLoading() {
if (isMainThread()) {
showView(mLoadingView, STATUS_LOADING);
} else {
post(new Runnable() {
@Override
public void run() {
showView(mLoadingView,STATUS_LOADING);
}
});
}
}
@Override
public void showLoading(int progress) {
if (isMainThread()) {
showView(mLoadingView, STATUS_LOADING);
showProgress(mLoadingView,progress);
} else {
post(new Runnable() {
@Override
public void run() {
showView(mLoadingView,STATUS_LOADING);
showProgress(mLoadingView,progress);
}
});
}
}
TextView tvLoading;
private void showProgress(View mLoadingView, int progress) {
try {
if(manager == null || manager.pageListener == null){
showP(mLoadingView,progress+"%");
return;
}
if(!manager.pageListener.showProgress(mEmptyView,progress)){
showP(mLoadingView,progress+"%");
}
}catch (Throwable throwable){
throwable.printStackTrace();
}
}
private void showP(View mLoadingView, String str) {
if(tvLoading != null){
tvLoading.setText(str);
return;
}
View tv = mLoadingView.findViewById(R.id.tv_msg_loading);
if(tv instanceof TextView){
tvLoading = (TextView) tv;
tvLoading.setText(str);
}
}
/**
* 会找到第一个textview,设置text. 如果msg为空,则不设置
*
* @param msg
*/
@Override
public void showError(final CharSequence msg) {
if (isMainThread()) {
showView(mRetryView,STATUS_ERROR);
setText(mRetryView, msg);
} else {
post(new Runnable() {
@Override
public void run() {
showView(mRetryView,STATUS_ERROR);
setText(mRetryView, msg);
}
});
}
}
private void setText(View view1, CharSequence msg) {
if (TextUtils.isEmpty(msg)) {
return;
}
if (view1 instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view1;
int count = viewGroup.getChildCount();
if (count > 0) {
for (int i = 0; i < count; i++) {
View view = viewGroup.getChildAt(i);
if (view instanceof TextView) {
TextView textView = (TextView) view;
textView.setText(msg);
return;
}
}
}
}
}
@Override
public void showContent() {
if (isMainThread()) {
showView(null,STATUS_CONTENT);
} else {
post(new Runnable() {
@Override
public void run() {
showView(null,STATUS_CONTENT);
}
});
}
}
@Override
public void showEmpty() {
if (isMainThread()) {
showView(mEmptyView,STATUS_EMPTY);
} else {
post(new Runnable() {
@Override
public void run() {
showView(mEmptyView,STATUS_EMPTY);
}
});
}
}
private void showView(View view, int status) {
if (this.status == status) {
return;
}
this.status = status;
if(status == STATUS_LOADING){
if(mLoadingView == null){
view = setLoadingView(manager.pageListener.customLoadingLayoutId());
}
}else if(status == STATUS_EMPTY){
if(mEmptyView == null){
view = setEmptyView(manager.pageListener.customEmptyLayoutId());
}
}else if(status == STATUS_ERROR){
if(mRetryView == null){
view = setRetryView(manager.pageListener.customErrorLayoutId());
}
}
if(contentViews.isEmpty()){
findContentViews();
}
if(status == STATUS_CONTENT){
if (mLoadingView != null)
mLoadingView.setVisibility(View.GONE);
if (mRetryView != null)
mRetryView.setVisibility(View.GONE);
if (mEmptyView != null)
mEmptyView.setVisibility(View.GONE);
showContentView();
return;
}
if (view == mLoadingView) {
mLoadingView.setVisibility(View.VISIBLE);
if (mRetryView != null)
mRetryView.setVisibility(View.GONE);
hideContentView();
if (mEmptyView != null)
mEmptyView.setVisibility(View.GONE);
} else if (view == mRetryView) {
mRetryView.setVisibility(View.VISIBLE);
if (mLoadingView != null)
mLoadingView.setVisibility(View.GONE);
hideContentView();
if (mEmptyView != null)
mEmptyView.setVisibility(View.GONE);
} else if (view == mEmptyView) {
mEmptyView.setVisibility(View.VISIBLE);
if (mLoadingView != null)
mLoadingView.setVisibility(View.GONE);
if (mRetryView != null)
mRetryView.setVisibility(View.GONE);
hideContentView();
}
setDarkMode(view);
}
private void setDarkMode(View view) {
if(view == null){
Log.w("setDarkMode","view is null!!!");
return;
}
if(manager != null && manager.pageListener != null){
if(manager.pageListener.darkMode()){
view.setBackgroundColor(Color.BLACK);
findChildTextviewAndSetWhite(view);
}
}
}
private void findChildTextviewAndSetWhite(View view) {
if(view instanceof ViewGroup){
ViewGroup viewGroup = (ViewGroup) view;
int childCount = viewGroup.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = viewGroup.getChildAt(i);
findChildTextviewAndSetWhite(child);
}
}else if(view instanceof TextView ){
TextView textView = (TextView) view;
textView.setTextColor(Color.WHITE);
Drawable background = textView.getBackground();
//Log.w("setDarkMode","background "+background);
if(background != null){
textView.setBackgroundColor(Color.parseColor("#333333"));
}
}
}
private void hideContentView() {
for (int i = 0; i < contentViews.size(); i++) {
contentViews.get(i).setVisibility(GONE);
}
}
private void showContentView() {
for (int i = 0; i < contentViews.size(); i++) {
contentViews.get(i).setVisibility(VISIBLE);
}
}
private void findContentViews() {
int count = getChildCount();
int contentCount = 0;
for (int i = 0; i < count; i++) {
View view = getChildAt(i);
if(view.equals(mEmptyView)){
continue;
}
if(view.equals(mLoadingView)){
continue;
}
if(view.equals(mRetryView)){
continue;
}
contentViews.add(view);
contentCount++;
}
if(contentCount == 0){
Log.w("pager","还没有设置contentview");
}
}
View setLoadingView(int layoutId) {
return setLoadingView(mInflater.inflate(layoutId, this, false));
}
View setEmptyView(int layoutId) {
return setEmptyView(mInflater.inflate(layoutId, this, false));
}
View setRetryView(int layoutId) {
return setRetryView(mInflater.inflate(layoutId, this, false));
}
View setLoadingView(View view) {
View loadingView = mLoadingView;
if (loadingView != null) {
Log.w(TAG, "you have already set a loading view and would be instead of this new one.");
}
removeView(loadingView);
addView(view,0);
mLoadingView = view;
return mLoadingView;
}
View setEmptyView(View view) {
View emptyView = mEmptyView;
if (emptyView != null) {
Log.w(TAG, "you have already set a empty view and would be instead of this new one.");
}
removeView(emptyView);
addView(view,0);
mEmptyView = view;
mEmptyView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (manager.pageListener != null) {
manager.pageListener.onEmtptyViewClicked(v);
}
}
});
return mEmptyView;
}
View setRetryView(View view) {
View retryView = mRetryView;
if (retryView != null) {
Log.w(TAG, "you have already set a retry view and would be instead of this new one.");
}
removeView(retryView);
addView(view,0);
mRetryView = view;
mRetryView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!NoNetworkHelper.isNetWorkAvailable(v.getContext())) {
NoNetworkHelper.showNoNetWorkDlg(v.getContext());
} else {
if (manager.pageListener != null) {
manager.pageListener.onRetry(v);
}
}
}
});
return mRetryView;
}
//给外部使用
View getErrorView() {
if(mRetryView == null){
setRetryView(manager.pageListener.customErrorLayoutId()).setVisibility(GONE);
}
return mRetryView;
}
View getLoadingView() {
if(mLoadingView == null){
setLoadingView(manager.pageListener.customLoadingLayoutId()).setVisibility(GONE);
}
return mLoadingView;
}
List getContentView() {
if(contentViews.isEmpty()){
findContentViews();
}
return contentViews;
}
View getEmptyView() {
if(mEmptyView == null){
setEmptyView(manager.pageListener.customEmptyLayoutId()).setVisibility(GONE);
}
return mEmptyView;
}
void setContentView(View oldContent) {
addView(oldContent);
contentViews.add(oldContent);
}
}
================================================
FILE: pagestate/src/main/res/drawable/loading_shadow.xml
================================================
================================================
FILE: pagestate/src/main/res/drawable/progressstyleshape.xml
================================================
================================================
FILE: pagestate/src/main/res/drawable/selector_btn_bg.xml
================================================
================================================
FILE: pagestate/src/main/res/layout/pager_empty.xml
================================================
================================================
FILE: pagestate/src/main/res/layout/pager_error.xml
================================================
================================================
FILE: pagestate/src/main/res/layout/pager_loading.xml
================================================
================================================
FILE: pagestate/src/main/res/values/strings.xml
================================================
pagestate#25808080No Network ConnectionTurn on your Network Connection or use Wi-Fi to access
data.
Go SettingsCancelloading…click to retrysome error occursopps, it seems that response is empty, go to see something else
================================================
FILE: pagestate/src/main/res/values-in/strings.xml
================================================
Tidak Ada JaringanNyalakan Koneksi Data Atau Sambungkan Wifi.PengaturanBatal
================================================
FILE: pagestate/src/main/res/values-ms/strings.xml
================================================
Tiada talianHidupkan talian internet anda atau gunakan WiFi untuk
mengakses data.
Layari tetapan andaSila batal
================================================
FILE: pagestate/src/main/res/values-vi/strings.xml
================================================
Không Kết nối mạngBật Kết nối mạng hoặc dùng Wi-Fi để lấy dữ liệu.Vào Cài đặtHủy
================================================
FILE: pagestate/src/main/res/values-zh/strings.xml
================================================
无网络打开网络连接或者wifi才能获取数据
去设置页取消加载中…点击重试发生了一些错误,请稍后重试咦…没有任何内容,先去逛逛别的吧
================================================
FILE: pagestate/src/test/java/com/hss01248/pagestate/ExampleUnitTest.java
================================================
package com.hss01248.pagestate;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
================================================
FILE: settings.gradle
================================================
include ':app', ':pagestate'