LoadSir


Source link: https://github.com/KingJA/LoadSir

English | ??

What's LoadSir?

👉👈

LoadSir is a lightweight, good expandable Android library used for displaying different pages like loading, error, empty, timeout or even your custom page when you load data from database or a REST service. LoadSir is very different from other similar libraries. I mean... better.

Preview - samples

in Activity in View in Fragment
Placeholder Multi-Fragment ViewPager+Fragment

Download Demo

Feature

  • ⭐? support for Activity, Fragment, Fragment(v4), View
  • ⭐? support for Multi-Fragment, Fragment+ViewPager
  • ⭐? convert http result structure into a Callback
  • ⭐? no need to modify the layout
  • ⭐? only load one layout once
  • ⭐? no need to set enum or constant for status code
  • ⭐? set your own onClick logic in custom Callback
  • ⭐? no preloaded load page
  • ⭐? support for keeping the toolbar, titleview
  • allow to customize your own load page
  • set the retry onClick listener OnReloadListener
  • set the default load page
  • add multi load pages
  • thread-safety

How does LoadSir work?

🚀 Getting started

LoadSir only needs 3 steps: 1. Config -> 2. Register -> 3. Display

Download

compile 'com.kingja.loadsir:loadsir:1.3.2'

Step 1: Config

There are two ways to set the config. Add your custom pages and set the default page.

  • Global Config

Set config with singleton pattern, you can do it in your Application. No matter where you do this job, you could get the unique LoadSir everywhere.

public class App extends Application {

  @Override
  public void onCreate() {

super.onCreate();

LoadSir.beginBuilder()

  .addCallback(new ErrorCallback())

  .addCallback(new EmptyCallback())

  .addCallback(new LoadingCallback())

  .addCallback(new TimeoutCallback())

  .addCallback(new CustomCallback())

  .setDefaultCallback(LoadingCallback.class)

  .commit();

  
}
 
}
  • Single Config

If you want to create another specific LoadSir, you can set config like this.

LoadSir loadSir = new LoadSir.Builder()

  .addCallback(new LoadingCallback())

  .addCallback(new EmptyCallback())

  .addCallback(new ErrorCallback())

  .build();
 loadService = loadSir.register(this, new Callback.OnReloadListener() {

  @Override
  public void onReload(View v) {

// retry logic
  
}
 
}
);

Step 2: Register

Tell LoadSir which "layout" you want to be replaced with LoadLayout.

  • Register an Activity

The registered Activity will be handled by LoadSir.

@Override protected void onCreate(@Nullable Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_content);

 // You can change the callback on sub thread directly.
  LoadService loadService = LoadSir.getDefault().register(this, new Callback.OnReloadListener() {

@Override

public void onReload(View v) {

 // your retry logic 

}

  
}
);
 
}
  • Register a View

The registered ImageView will be handled by LoadSir.

ImageView imageView = (ImageView) findViewById(R.id.iv_img);
 LoadSir loadSir = new LoadSir.Builder()

.addCallback(new TimeoutCallback())

.setDefaultCallback(LoadingCallback.class)

.build();
 loadService = loadSir.register(imageView, new Callback.OnReloadListener() {

  @Override
  public void onReload(View v) {

loadService.showCallback(LoadingCallback.class);

// your retry logic
  
}
 
}
);
  • Register a Fragment

The registered Fragment will be handled by LoadSir. Use it in Fragment is a bit different from the other two, follow the template code.

@Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

  //step 1?obtain root view
  rootView = View.inflate(getActivity(), R.layout.fragment_a_content, null);

 //step 2?obtain the LoadService
  LoadService loadService = LoadSir.getDefault().register(rootView, new Callback.OnReloadListener() {

@Override

public void onReload(View v) {

 // your retry logic

}

  
}
);

 //step 3?return the LoadLayout from LoadService
  return loadService.getLoadLayout();
 
}

Step 3: Display

What to show after fetching data (from REST service or database...)?

  • Direct Display
protected void loadFromNet() {

  // do net job/load data...

// callback after finish
  loadService.showSuccess();
 // successful case -> show the data, eg RecyclerView,...
  --- OR ---
  loadService.showCallback(EmptyCallback.class);
 // do/show something else 
}

Info: showSuccess() calls the SuccessCallback to "hide" LoadSir and show the content.

  • Convertor Display (recommended)

If you want LoadSir to do callback automatically, you can pass a Convertor when you register.

LoadService loadService = LoadSir.getDefault().register(this, new Callback.OnReloadListener() {

  @Override
  public void onReload(View v) {

 // retry logic
  
}

}
, new Convertor<HttpResult>() {

  @Override
  public Class<? extends Callback> map(HttpResult httpResult) {

Class<? extends Callback> resultCode = SuccessCallback.class;

switch (httpResult.getResultCode()) {

 case SUCCESS_CODE:

  if (httpResult.getData().size() == 0) {

resultCode = EmptyCallback.class;

  
}
else{

resultCode = SuccessCallback.class;

  
}

  break;

 case ERROR_CODE:

  resultCode = ErrorCallback.class;

  break;

}

return resultCode;
  
}
 
}
);

Pass a HttpResult, now you start up a robot LoadSir.

loadService.showWithConvertor(httpResult);

Customize

You can customize your own load page like loading, empty, error, timeout, etc. Provide the layout and fill the retry logic (if necessarily).

public class CustomCallback extends Callback {

@Override
  protected int onCreateView() {

return R.layout.layout_custom;
  
}

@Override
  protected boolean onReloadEvent(final Context context, View view) {

Toast.makeText(context.getApplicationContext(), "Hello buddy! :p", Toast.LENGTH_SHORT).show();

(view.findViewById(R.id.iv_gift)).setOnClickListener(new View.OnClickListener() {

 @Override

 public void onClick(View v) {

  Toast.makeText(context.getApplicationContext(), "It's your gift! :p", Toast.LENGTH_SHORT).show();

 
}

}
);

return true;
  
}

//set visibility of SuccessView when callback is attach to Layout,true:visible, false: invisible
  @Override
  public boolean getSuccessVisible() {

return super.getSuccessVisible();

  
}

//Called when the view of Callback is attached to LoadLayout.
  @Override
  public void onAttach(Context context, View view) {

super.onAttach(context, view);

  
}

//Called when the view of Callback was detached from LoadLayout.
  @Override
  public void onDetach() {

super.onDetach(context, view);

  
}
  
}

Modify Callback Dynamically

Access the view of a Callback.

loadService = LoadSir.getDefault().register(...);
 loadService.setCallBack(EmptyCallback.class, new Transport() {

 @Override
 public void order(Context context, View view) {

  TextView mTvEmpty = (TextView) view.findViewById(R.id.tv_empty);

  mTvEmpty.setText("Fine, no data. You must fill it!");

 
}
 
}
);

Default Callback in LoadSir

ProgressCallback loadingCallback = new ProgressCallback.Builder()

.setTitle("Loading", R.style.Hint_Title)

.build();
  HintCallback hintCallback = new HintCallback.Builder()

.setTitle("Error", R.style.Hint_Title)

.setSubTitle("Sorry, buddy, I will try it again.")

.setHintImg(R.drawable.error)

.build();
  LoadSir loadSir = new LoadSir.Builder()

.addCallback(loadingCallback)

.addCallback(hintCallback)

.setDefaultCallback(ProgressCallback.class)

.build();

💡 About placeholder effect

The effect of placeholder is just like the library ShimmerRecyclerView works. LoadSir do the similar job only through a PlaceHolderCallback, just a custom Callback. That feeling was amazing. 👻

Docs

ProGuard

-dontwarn com.kingja.loadsir.** -keep class com.kingja.loadsir.** {
*;
}

Contact Me

Any questions: Welcome to contact me.

License

Copyright 2017 KingJA  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. 

Resources

A menu layout view with FloatingActionButton, which means you still can use the features of FAB like auto hide while scrolling.

Pan

A light weight MV* framework to build android reusable UI components.

rog

Rog is an object generator designed for android test. It can create objects and set random values to their fields.

Spark is a simple Android library that takes a series of x,y points at any scale and draws them as a sparkline chart.

It's a framework for building Android UI in Kotlin code by using the concept of virtual views and reactive data flow, the goal is to reduce boilerplate while retaining the same Android layout constructs.

EasyIntro is the flexible, easy to use, all in one app intro library for your Android project.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes