MultiType


Source link: https://github.com/drakeet/MultiType

MultiType

An Android library to create multiple item types list views easily and flexibly.

English Version | ?Android ?????????? · ????

Previously, when we need to develop a complex RecyclerView / ListView, it is a difficult and troublesome work. We should override the getItemViewType() of RecyclerView.Adapter , add some types, and create some ViewHolders relating to those types. The process is cumbersome.

Once we need to add a new item type, we have to go to the original adapter and modify some old codes, and adapter classes will be bulkier.

Today, I created a new intuitive and flexible way to easily create complex RecyclerViews, with the MultiType library, we could insert a new item type without changing the old adapter codes and make them more readable.

Getting started

In your build.gradle:

dependencies {

  implementation 'me.drakeet.multitype:multitype:3.4.0' 
}

If you are using com.android.tools.build:gradle:2.+, use this instead:

dependencies {

  compile 'me.drakeet.multitype:multitype:3.4.0' 
}

Note: MultiType does not support RecyclerView below version 23.0.0.

Usage

Step 1. Create a class, It would be your data model/ Java bean, for example:

public class TextItem {

public @NonNull final String text;

public TextItem(@NonNull String text) {

this.text = text;
  
}
 
}

Step 2. Create a class extends ItemViewBinder<T, VH extends ViewHolder>, for example:

public class TextItemViewBinder extends ItemViewBinder<TextItem, TextItemViewBinder.TextHolder> {

static class TextHolder extends RecyclerView.ViewHolder {

  private @NonNull final TextView text;

 TextHolder(@NonNull View itemView) {

 super(itemView);

 this.text = (TextView) itemView.findViewById(R.id.text);

}

  
}

@NonNull @Override
  protected TextHolder onCreateViewHolder(@NonNull LayoutInflater inflater, @NonNull ViewGroup parent) {

View root = inflater.inflate(R.layout.item_text, parent, false);

return new TextHolder(root);

  
}

@Override
  protected void onBindViewHolder(@NonNull TextHolder holder, @NonNull TextItem textItem) {

holder.text.setText("hello: " + textItem.text);

Log.d("demo", "position: " + getPosition(holder));

Log.d("demo", "adapter: " + getAdapter());

  
}
 
}

Step 3. Just register your types and setup your RecyclerView and List<Object> in your Activity, for example:

public class SampleActivity extends AppCompatActivity {

private MultiTypeAdapter adapter;
  private Items items;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list);

 adapter = new MultiTypeAdapter();

adapter.register(TextItem.class, new TextItemViewBinder());

adapter.register(ImageItem.class, new ImageItemViewBinder());

adapter.register(RichItem.class, new RichItemViewBinder());

recyclerView.setAdapter(adapter);

 /* Mock the data */

TextItem textItem = new TextItem("world");

ImageItem imageItem = new ImageItem(R.mipmap.ic_launcher);

RichItem richItem = new RichItem("??????", R.mipmap.avatar);

 items = new Items();

for (int i = 0; i < 20; i++) {

 items.add(textItem);

 items.add(imageItem);

 items.add(richItem);

}

adapter.setItems(items);

adapter.notifyDataSetChanged();

  
}
 
}

That's all, you're good to go!

Advanced usage

One to many:

adapter.register(Data.class).to(
  new DataType1ViewBinder(),
  new DataType2ViewBinder() ).withLinker((position, data) ->
  data.type == Data.TYPE_2 ? 1 : 0 );
adapter.register(Data.class).to(
  new DataType1ViewBinder(),
  new DataType2ViewBinder() ).withClassLinker((position, data) -> {

  if (data.type == Data.TYPE_2) {

return DataType2ViewBinder.class;
  
}
 else {

return DataType1ViewBinder.class;
  
}
 
}
);

Wiki

Change Log

https://github.com/drakeet/MultiType/releases

Android Studio Plugin

An intellij idea plugin for Android to generate MultiType Item and ItemViewBinder easily.

Sample screenshots

You could check the sample module for more details and after running it will look like:

And it has been used in drakeet/TimeMachine:

License

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

Proteus is meant to be a drop-in replacement for Android’s LayoutInflater; but unlike the compiled XML layouts bundled in the APK, Proteus inflates layouts at runtime.

With Proteus, you can control your Apps layout from the backend (no WebViews). Forget the boilerplate code to findViewById, cast it to a TextView, and then setText(). Proteus has runtime data bindings and formatters. Plugin in your own custom views and attributes and formatters.

SmartDeviceLink (SDL) is a standard set of protocols and messages that connect applications on a smartphone to a vehicle head unit. This messaging enables a consumer to interact with their application using common in-vehicle interfaces such as a touch screen display, embedded voice recognition, steering wheel controls and various vehicle knobs and buttons. There are three main components that make up the SDL ecosystem.

Simple custom ImageView for android giving you a simple way to enable overlapping of two images one over the other.

OkHttp-Stats is an android library built on top of OkHttp3, which is responsible for intercepting all the network calls and for calculating network stats such as the average network speed of the user.

This is more of an analytical tool which can be used to track the success and error response logs.

Can be plugged in to any app which uses okhttp in their networking stack.

Example app to use Protobuf in Android using Square's Wire library.

Espresso's consistency makes it really easy to learn.

Want to match a view with a specific id? Use withId(R.id.some_id). Need to match with a piece of text? Use withText(R.id.some_text) or withText("some text). Awesome, consistent and it's very clear what it is you are doing.

However...

After a few hours writing test code you'll find your code being a little bit too verbose. Not anymore.

Why should you need to explicitly specify that you are matching with some text if you are passing in some text as a parameter? Some for the view id, you can already see that it is a view id.

Ristretto allows you to write the same test code as you already write, but less verbose.

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