Banner 2.0 Android Carousel Library

repository·master·Indexed 12 days ago

https://github.com/youth5201314/banner

A highly customizable Android carousel and banner library built on ViewPager2. It supports androidx compatibility, horizontal and vertical scrolling, and built-in PageTransformer effects such as Gallery, Meizu, and Toutiao styles. Version 2.2.3 provides flexible UI and indicator customization via Java/Kotlin code or XML attributes.

Tokens
4.7K
Snippets
8
Records
12
Agent score
46%

What's inside Banner

  1. Overview of Banner 2.0

    master

    Banner 2.0 is a highly customizable carousel container for Android that does not intrude on your UI. It is built on top of ViewPager2 and provides a variety of built-in effects and easy customization for both the UI and indicators.

    Key features include:

    • Built on ViewPager2 for better performance.
    • Supports androidx compatibility.
    • Easy customization of UI and Indicators.
    • Built-in effects like Gallery, Meizu, and Toutiao-style layouts.
    • Supports both horizontal and vertical scrolling.
    • Built-in PageTransformer effects.
  2. Built-in PageTransformer effects

    master

    Banner 2.0 includes several built-in PageTransformer implementations to control the transition animation between pages. You can use setPageTransformer(PageTransformer) to set a single effect or addPageTransformer(PageTransformer) to combine multiple effects.

    Available built-in transformers:

    • AlphaPageTransformer
    • DepthPageTransformer
    • RotateDownPageTransformer
    • RotateUpPageTransformer
    • RotateYTransformer
    • ScaleInTransformer
    • ZoomOutPageTransformer
  3. Manage Banner Lifecycle

    master

    To ensure the banner starts and stops scrolling correctly with your Activity/Fragment lifecycle, you have two options:

    1. Automatic: Call banner.addBannerLifecycleObserver(this). This is the recommended way as it lets the banner manage its own lifecycle.
    2. Manual: Call banner.start(), banner.stop(), and banner.destroy() within your Activity's onStart(), onStop(), and onDestroy() methods respectively.
    // Method 1: Automatic lifecycle management
    protected void onCreate(Bundle savedInstanceState) {
         banner.addBannerLifecycleObserver(this);
    }
    
    // Method 2: Manual control
    @Override
    protected void onStart() {
        super.onStart();
        banner.start();
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        banner.stop();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        banner.destroy();
    }
  4. Add Banner to Layout

    master

    You can add the Banner component to your XML layout files using the com.youth.banner.Banner tag. Alternatively, you can instantiate it directly in an Activity or Fragment.

    <com.youth.banner.Banner
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/banner"
        android:layout_width="match_parent"
        android:layout_height="HEIGHT_VALUE" />
  5. Add Internet Permission

    master

    If you intend to load images from the internet within your Banner, ensure you have the INTERNET permission declared in your AndroidManifest.xml.

    <!-- if you want to load images from the internet -->
    <uses-permission android:name="android.permission.INTERNET" /> 
  6. Install Banner via Gradle

    master

    To use Banner in your Android project, add the Maven Central repository and the dependency to your build.gradle file. Note that older versions (2.1.0 and below) used JCenter, but current versions are hosted on Maven Central.

    repositories {
        maven { url "https://s01.oss.sonatype.org/content/groups/public" }
    }
    
    dependencies{
        // Current version on Maven Central
        implementation 'io.github.youth5201314:banner:2.2.3'
    }
  7. Troubleshoot Banner Issues

    master

    Network Images Not Loading

    Banner does not provide image loading functionality. Ensure your image loading library (like Glide or Picasso) is configured correctly and check for HTTPS/SSL certificate errors if loading from a server.

    Specifying Start Position

    Use setStartPosition() when calling setAdapter or setDatas. Alternatively, use setCurrentItem() after the adapter is set.

    Preventing Focus Issues in Parent Layouts

    If the banner causes the parent layout to grab focus and auto-scroll, add these attributes to the parent container:

    android:focusable="true"
    android:focusableInTouchMode="true"

    Setting Rounded Corners

    There are two ways to set rounded corners:

    1. Use the provided Banner methods or XML attributes to set the corner radius of the Banner container itself.
    2. Implement rounded corners within your Adapter (e.g., by using a custom ImageView or applying a transformation in Glide) to round the content inside the banner.
  8. Initialize and Use Banner

    master

    To use the Banner, you typically set an adapter and an indicator. For simple image scrolling, you can use the built-in BannerImageAdapter to reduce boilerplate code.

    // Standard usage with custom adapter
    banner.addBannerLifecycleObserver(this)
            .setAdapter(new BannerExampleAdapter(DataBean.getTestData()))
            .setIndicator(new CircleIndicator(this));
    
    // Simplified usage for image scrolling only
    banner.setAdapter(new BannerImageAdapter<DataBean>(DataBean.getTestData3()) {
                @Override
                public void onBindView(BannerImageHolder holder, DataBean data, int position, int size) {
                    // Use your preferred image loading library (e.g., Glide)
                    Glide.with(holder.itemView)
                         .load(data.imageUrl)
                         .apply(RequestOptions.bitmapTransform(new RoundedCorners(30)))
                         .into(holder.imageView);
                }
            })
            .addBannerLifecycleObserver(this)
            .setIndicator(new CircleIndicator(this));
  9. Implement a Custom BannerAdapter

    master

    To display custom layouts, extend BannerAdapter<T, VH>. This is similar to a RecyclerView.Adapter. You must implement onCreateHolder and onBindView.

    Note: When using ViewPager2, the layout params for the view inside the holder must be set to MATCH_PARENT.

    /**
     * Custom layout implementation
     */
    public class ImageAdapter extends BannerAdapter<DataBean, ImageAdapter.BannerViewHolder> {
    
        public ImageAdapter(List<DataBean> mDatas) {
            super(mDatas);
        }
    
        @Override
        public BannerViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            ImageView imageView = new ImageView(parent.getContext());
            // Must be MATCH_PARENT for ViewPager2 requirements
            imageView.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return new BannerViewHolder(imageView);
        }
    
        @Override
        public void onBindView(BannerViewHolder holder, DataBean data, int position, int size) {
            holder.imageView.setImageResource(data.imageRes);
        }
    
        class BannerViewHolder extends RecyclerView.ViewHolder {
            ImageView imageView;
    
            public BannerViewHolder(@NonNull ImageView view) {
                super(view);
                this.imageView = view;
            }
        }
    }
  10. Banner API Reference

    master

    The following methods are available on the Banner instance to control its behavior, data, and appearance. Note that some methods (like getIndicator) may throw exceptions if an indicator has not been set.

    | Method | Return Type | Description |
    |---|---|---|
    | `getAdapter()` | `extends BannerAdapter` | Get the set `BannerAdapter` |
    | `getViewPager2()` | `ViewPager2` | Get the underlying `ViewPager2` |
    | `getIndicator()` | `Indicator` | Get the set `Indicator` (throws exception if not set) |
    | `getIndicatorConfig()` | `IndicatorConfig` | Get the set `IndicatorConfig` (throws exception if not set) |
    | `getRealCount()` | `int` | Return the actual total number of items |
    | `setUserInputEnabled(boolean)` | `this` | Enable (`true`) or disable (`false`) manual sliding |
    | `setDatas(List<T>)` | `this` | Re-set the banner data |
    | `isAutoLoop(boolean)` | `this` | Set whether auto-looping is enabled |
    | `setLoopTime(long)` | `this` | Set loop interval (default 3000ms) |
    | `setScrollTime(long)` | `this` | Set scroll duration (default 800ms) |
    | `start()` | `this` | Start looping (use with lifecycle) |
    | `stop()` | `this` | Stop looping (use with lifecycle) |
    | `setAdapter(T extends BannerAdapter)` | `this` | Set the adapter |
    | `setAdapter(T extends BannerAdapter, boolean)` | `this` | Set the adapter and whether infinite loop is supported |
    | `setOrientation(@Orientation)` | `this` | Set orientation (vertical or horizontal) |
    | `setOnBannerListener(this)` | `this` | Set click listener (index starts at 0) |
    | `addOnPageChangeListener(this)` | `this` | Add `ViewPager2` scroll listener |
    | `setPageTransformer(PageTransformer)` | `this` | Set the page transition effect |
    | `addPageTransformer(PageTransformer)` | `this` | Add a page transition effect (can add multiple) |
    | `setIndicator(Indicator)` | `this` | Set the indicator (supports custom implementations) |
    | `setIndicator(Indicator, boolean)` | `this` | Set indicator; `false` means do not add indicator to banner (use with custom layout) |
    | `setIndicatorSelectedColor(@ColorInt)` | `this` | Set selected indicator color |
    | `setIndicatorSelectedColorRes(@ColorRes)` | `this` | Set selected indicator color via resource |
    | `setIndicatorNormalColor(@ColorInt)` | `this` | Set normal indicator color |
    | `setIndicatorNormalColorRes(@ColorRes)` | `this` | Set normal indicator color via resource |
    | `setIndicatorGravity(@IndicatorConfig.Direction)` | `this` | Set indicator position (Left, Center, Right) |
    | `setIndicatorSpace(int)` | `this` | Set spacing between indicators |
    | `setIndicatorMargins(IndicatorConfig.Margins)` | `this` | Set indicator margins |
    | `setIndicatorWidth(int, int)` | `this` | Set selected and unselected widths |
    | `setIndicatorNormalWidth(int)` | `this` | Set unselected indicator width |
    | `setIndicatorSelectedWidth(int)` | `this` | Set selected indicator width |
    | `setIndicatorRadius(int)` | `this` | Set indicator corner radius (0 for no radius) |
    | `setIndicatorHeight(int)` | `this` | Set indicator height |
    | `setBannerRound(float)` | `this` | Set banner corner radius (use `setBannerRound2` for API 5.0+) |
    | `setBannerGalleryEffect(int, int, float)` | `this` | Set Gallery effect |
    | `setBannerGalleryMZ(int, float)` | `this` | Set Meizu effect |
    | `setStartPosition(int)` | `this` | Set start position (must call before `setAdapter` or `setDatas`) |
    | `setIndicatorPageChange()` | `this` | Set indicator change listener |
    | `setCurrentItem()` | `this` | Set current item position |
    | `addBannerLifecycleObserver()` | `this` | Add lifecycle observer for automatic lifecycle management |
  11. Configure Banner via XML Attributes

    master

    You can configure many Banner properties directly in your XML layout file using the banner_ prefix. Note that not all attributes are supported by every custom indicator.

    AttributeFormatDescription
    banner_loop_timeintegerLoop interval (default 3000)
    banner_auto_loopbooleanEnable auto-loop (default true)
    banner_infinite_loopbooleanSupport infinite loop (default true)
    banner_orientationenumhorizontal (default) or vertical
    banner_radiusdimensionBanner corner radius (default 0)
    banner_indicator_normal_widthdimensionNormal indicator width (default 5dp, invalid for RoundLinesIndicator)
    banner_indicator_selected_widthdimensionSelected indicator width (default 7dp)
    banner_indicator_normal_colorcolorNormal indicator color (default 0x88ffffff)
    banner_indicator_selected_colorcolorSelected indicator color (default 0x88000000)
    banner_indicator_spacedimensionSpacing between indicators (default 5dp, invalid for RoundLinesIndicator)
    banner_indicator_gravitydimensionIndicator position (default center)
    banner_indicator_margindimensionIndicator margin (default 5dp, cannot be used with specific margin attributes)
    banner_indicator_marginLeftdimensionLeft margin
    banner_indicator_marginTopdimensionTop margin
    banner_indicator_marginRightdimensionRight margin
    banner_indicator_marginBottomdimensionBottom margin
    banner_indicator_heightdimensionIndicator height (invalid for CircleIndicator)
    banner_indicator_radiusdimensionIndicator corner radius (invalid for CircleIndicator)
    banner_round_top_leftbooleanDraw corner for top-left
    banner_round_top_rightbooleanDraw corner for top-right
    banner_round_bottom_leftbooleanDraw corner for bottom-left
    banner_round_bottom_rightbooleanDraw corner for bottom-right