Gloading
Show global loading status view in a low coupling way for Android App.
Lightweight: aar is less than 6KB, just 170 code lines and 104 comment lines within only 1 java file.
Design as Adapter pattern, with good compatibility: most third-party LoadingViews can be used as Gloading views in the Adapter.
Wrap activity page
Load success | Load failed and click retry | Load success with empty data | This loading status UI is special |
---|---|---|---|
![]() |
![]() |
![]() |
![]() |
Wrap view(s)
Wrap single view | Wrap views | Wrap in GridView | Wrap in RecyclerView No words below |
---|---|---|---|
![]() |
![]() |
![]() |
![]() |
compile 'com.billy.android:gloading:1.0.0'
For global usage, create an Adapter to provide views for all status via getView(...) method.
Note: Activity/Fragment/View reused in 2 or more apps with different loading status views?
Just provide a different Adapter for each app.
No need to change any usage code
demo
public class GlobalAdapter implements Gloading.Adapter {
@Override
public View getView(Gloading.Holder holder, View convertView, int status) {
GlobalLoadingStatusView loadingStatusView = null;
//reuse the old view, if possible
if (convertView != null && convertView instanceof GlobalLoadingStatusView) {
loadingStatusView = (GlobalLoadingStatusView) convertView;
}
if (loadingStatusView == null) {
loadingStatusView = new GlobalLoadingStatusView(holder.getContext(), holder.getRetryTask());
}
loadingStatusView.setStatus(status);
return loadingStatusView;
}
class GlobalLoadingStatusView extends RelativeLayout {
public GlobalLoadingStatusView(Context context, Runnable retryTask) {
super(context);
//init view ...
}
public void setStatus(int status) {
//change ui by different status...
}
}
}
See demo code.
Gloading.initDefault(new GlobalAdapter());
Note: Use AutoRegister to decoupling this step.
3.1 Wrap something and return a Gloading.Holder object
//Gloading wrapped whole activity, wrapper view: android.R.id.content
Gloading.Holder holder = Gloading.getDefault().wrap(activity);
//with load failed retry task
Gloading.Holder holder = Gloading.getDefault().wrap(activity).withRetry(retryTask);
or
//Gloading will create a FrameLayout to wrap it
Gloading.Holder holder = Gloading.getDefault().wrap(view);
//with load failed retry task
Gloading.Holder holder = Gloading.getDefault().wrap(view).withRetry(retryTask);
3.2 Show status views for loading/loadFailed/empty/... by Gloading.Holder
//show loading status view by holder
holder.showLoading()
//show load success status view by holder (frequently, hide gloading)
holder.showLoadSuccess()
//show load failed status view by holder (frequently, needs retry task)
holder.showFailed()
//show empty status view by holder. (load completed, but data is empty) **holder.showEmpty()**
More Gloading.Holder APIs
public abstract class BaseActivity extends Activity {
protected Gloading.Holder mHolder;
/**
* Сделайте обёртку Gloading.Holder с текущей активностью по умолчанию
* Переопределите этот метод в подклассе, чтобы выполнить специальную инициализацию
*/
protected void initLoadingStatusViewIfNeed() {
if (mHolder == null) {
// привяжите представление состояния к корневому представлению активности по умолчанию
mHolder = Gloading.getDefault().wrap(this).withRetry(new Runnable() {
@Override
public void run() {
onLoadRetry();
}
});
}
}
protected void onLoadRetry() {
// переопределите этот метод в подклассе для выполнения задачи повтора
}
public void showLoading() {
initLoadingStatusViewIfNeed();
mHolder.showLoading();
}
public void showLoadSuccess() {
initLoadingStatusViewIfNeed();
mHolder.showLoadSuccess();
}
public void showLoadFailed() {
initLoadingStatusViewIfNeed();
mHolder.showLoadFailed();
}
public void showEmpty() {
initLoadingStatusViewIfNeed();
mHolder.showEmpty();
}
}
public class GlobalFailedActivity extends BaseActivity {
private ImageView imageView;
private String picUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//do sth init...
loadData();
}
private void loadData() {
showLoading();
loadDataAndCallback(new Callback() {
public void success(Data data) {
if (isEmpty(data)) {
showEmpty();
} else {
//do sth with data...
showLoadSuccess();
}
}
public void failed() {
//do sth...
showLoadFailed();
}
});
}
@Override
protected void onLoadRetry() {
loadData();
}
//other codes...
}
//режим отладки. если установлено значение true, журналы будут выводиться в logcat
Gloading.debug(trueOrFalse);
Изображения в демонстрационном приложении взяты из: https://www.thiswaifudoesnotexist.net/
Глобальные изображения LoadingView в демо-версии взяты из: https://www.iconfont.cn/
Специальный пользовательский интерфейс LoadingView, используемый в демонстрации, взят из: https://github.com/ldoublem/LoadingView/
Вы можете оставить комментарий после Вход в систему
Неприемлемый контент может быть отображен здесь и не будет показан на странице. Вы можете проверить и изменить его с помощью соответствующей функции редактирования.
Если вы подтверждаете, что содержание не содержит непристойной лексики/перенаправления на рекламу/насилия/вульгарной порнографии/нарушений/пиратства/ложного/незначительного или незаконного контента, связанного с национальными законами и предписаниями, вы можете нажать «Отправить» для подачи апелляции, и мы обработаем ее как можно скорее.
Комментарии ( 0 )