Toro


Source link: https://github.com/eneim/Toro

Toro

Video list auto playback made simple, specially built for RecyclerView

Menu

Features

  • Auto start/pause Media playback on Attach/Detach/Scroll/... events.
  • Optional playback position save/restore (no position save/restore by default).
    • If enabled, Toro will also save/restore them on Configuration change (orientation change, multi-window mode ...).
  • Customizable playback component: either MediaPlayer or ExoPlayer will work. Toro comes with default helper classes to support these 2.
  • Customizable player selector: custom the selection of the player to start, among many other players.
    • Which in turn support single/multiple players.
  • First class Support ExoPlayer 2.

Demo (Youtube Video)

Getting start

  1. Update module build.gradle.

Latest version:

ext {
   toroVersion = '3.0.0'
// below: other dependencies' versions maybe 
}
  dependencies {

 compile "im.ene.toro3:toro:${
toroVersion
}
" // deprecated in Android Studio 3.0

  // TODO: uncomment if using Android Studio 3.+ only
 // implementation "im.ene.toro3:toro:${
toroVersion
}
" 
}
  1. Using Container in place of Video list.
<im.ene.toro.widget.Container   android:id="@+id/my_fancy_videos"
android:layout_width="match_parent"
android:layout_height="match_parent" />
  1. Implement ToroPlayer to ViewHolder that should be a Video player.
public class SimpleExoPlayerViewHolder extends RecyclerView.ViewHolder implements ToroPlayer {

 static final int LAYOUT_RES = R.layout.vh_exoplayer_basic;
 @Nullable SimpleExoPlayerViewHelper helper;
@Nullable private Uri mediaUri;
 @BindView(R.id.player) SimpleExoPlayerView playerView;
 SimpleExoPlayerViewHolder(View itemView) {
     super(itemView);
     ButterKnife.bind(this, itemView);

}

 // called from Adapter to setup the media   void bind(@NonNull RecyclerView.Adapter adapter, Uri item, List<Object> payloads) {

  if (item != null) {

 mediaUri = item;
  
}

}

 @NonNull @Override public View getPlayerView() {

  return playerView;

}

 @NonNull @Override public PlaybackInfo getCurrentPlaybackInfo() {

  return helper != null ? helper.getLatestPlaybackInfo() : new PlaybackInfo();

}

 @Override
public void initialize(@NonNull Container container, @Nullable PlaybackInfo playbackInfo) {

  if (helper == null) {

 helper = new SimpleExoPlayerViewHelper(container, this, mediaUri);

  
}

  helper.initialize(playbackInfo);

}

 @Override public void release() {

  if (helper != null) {

 helper.release();

 helper = null;
  
}

}

 @Override public void play() {

  if (helper != null) helper.play();

}

 @Override public void pause() {

  if (helper != null) helper.pause();

}

 @Override public boolean isPlaying() {

  return helper != null && helper.isPlaying();

}

 @Override public boolean wantsToPlay() {

  return ToroUtil.visibleAreaOffset(this, itemView.getParent()) >= 0.85;

}

 @Override public int getPlayerOrder() {

  return getAdapterPosition();

}
 
}

More advanced View holder implementations can be found in app module.

  1. Setup Adapter to use the ViewHolder above, and setup Container to use that Adapter.

That's all. Your View should be ready to play.

Advance usage and class documentation (I need your request to update this list)

  1. Enable playback position save/restore: using CacheManager

The implementation is simple: create a class implementing CacheManager, then set it to the Container using Container#setCacheManager(CacheManager). Sample code can be found in TimelineAdapter.java. Note that here I implement the interface right into the Adapter for convenience. It can be done without Adapter. There is one thing worth noticing: a matching between playback order with its cached playback info should be unique.

  1. Multiple simultaneous playback

Playing multiple Videos at once is considered bad practice. It is a heavy power consuming task and also unfriendly to hardware. In fact, each device has its own limitation of multiple decoding ability, so developer must be aware of what you are doing. I don't officially support this behaviour. Developer should own the video source to optimize the video for this purpose.

To be able to have more than one Video play at the same time, developer must use a custom PlayerSelector. This can also provide a powerful control to number of playback in a dynamic way.

Below is an example using GridLayoutManager and custom PlayerSelector to have a fun multiple playback.

layoutManager = new GridLayoutManager(getContext(), 2);
 layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {

@Override public int getSpanSize(int position) {

  return position % 3 == 2 ? 2 : 1;

}
 
}
);
  // A custom Selector to work with Grid span: even row will has 2 Videos while odd row has one Video. // This selector will select all videos available for each row, which will make the number of Players varies. PlayerSelector selector = new PlayerSelector() {

@NonNull @Override public Collection<ToroPlayer> select(@NonNull View container,

 @NonNull List<ToroPlayer> items) {

  List<ToroPlayer> toSelect;
  int count = items.size();

  if (count < 1) {

 toSelect = Collections.emptyList();

  
}
 else {

 int firstOrder = items.get(0).getPlayerOrder();

 int span = layoutManager.getSpanSizeLookup().getSpanSize(firstOrder);

 count = Math.min(count, layoutManager.getSpanCount() / span);

 toSelect = new ArrayList<>();

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

toSelect.add(items.get(i));

 
}

  
}

return toSelect;

}

 @NonNull @Override public PlayerSelector reverse() {

  return this;

}
 
}
;  container.setPlayerSelector(selector);

Behaviour:

  1. Enable/Disable the autoplay on demand.

To disable the autoplay, simply use the PlayerSelector.NONE for the Container. To enable it again, just use a Selector that actually select the player. There is PlayerSelector.DEFAULT built-in.

Contribution

  • IMPORTANT: Forkers of Toro should also rename file gradle.properties-sample to gradle.properties before any build.

  • Issue report and Pull Requests are welcome. Please follow issue format for quick response.

  • For Pull Requests, this project uses 2-space indent and no Hungarian naming convention.

Donation

  • You can always buy me some coffee for shorter update cycle ...

Hall of Fame

Email to [email protected] with the description of your App using Toro to list it here.

License

Copyright 2017 eneim@Eneim Labs, [email protected]

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

Android Code Highlighter.

How to create instagram like Gradient color transition in android.

This is an Android Library for developer to use customized recyclerview with many features, like easy use Empty view, Refresh view, Floating Action Button, Load more. So all these features contain in one recyclerview.

In short, this is a GraphQL request JSON body builder for Kotlin. It will generate the JSON string for request body that work with GraphQL Server.

An easy way to check the settings before requesting location using RxJava. Based on Android-ReactiveLocation.

Gradle Script Kotlin provides support for writing Gradle build scripts using JetBrains' Kotlin language. It aims to provide Gradle users with a rich, flexible and statically-typed approach to developing build logic in conjunction with the best IDE and tooling experience possible.

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