Android Custom Banner Carousel Effect

  • 2021-09-05 00:46:16
  • OfStack

In this paper, we share the specific codes of Android custom Banner carousel effect display for your reference. The specific contents are as follows

Custom View layout


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="wrap_content">

  <android.support.v4.view.ViewPager
    android:id="@+id/banner_view_pager"
    android:layout_width="match_parent"
    android:layout_height="200dp">

  </android.support.v4.view.ViewPager>

  <LinearLayout
    android:id="@+id/linear_bannner"
    android:layout_centerHorizontal="true"
    android:layout_alignBottom="@+id/banner_view_pager"
    android:layout_marginBottom="10dp"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

  </LinearLayout>


</RelativeLayout>

Customize View body content


public class CustomBanner extends FrameLayout {

  @BindView(R.id.banner_view_pager)
  ViewPager bannerViewPager;
  @BindView(R.id.linear_bannner)
  LinearLayout linearBannner;
  private List<String> list;
  private int time = 2;

  private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      if (msg.what == 0) {

        int currentItem = bannerViewPager.getCurrentItem();

        bannerViewPager.setCurrentItem(currentItem + 1);

        // Send again 
        sendEmptyMessageDelayed(0, time * 1000);

      }
    }
  };
  private List<ImageView> listDoc;
  private OnClickLisner onClickLisner;

  public CustomBanner(@NonNull Context context) {
    super(context);
    init();
  }

  public CustomBanner(@NonNull Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    init();
  }

  public CustomBanner(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
  }

  /**
   *  Initialization 
   */
  private void init() {

    View view = View.inflate(getContext(), R.layout.bannner_layout, this);
    ButterKnife.bind(this, view);

  }

  /**
   *  Provide settings externally image Method of path 
   */
  public void setImageUrls(List<String> list) {
    this.list = list;

    if (list == null) {
      return;
    }

    // Setting adapter 
    LunBoAdapter lunBoAdapter = new LunBoAdapter(getContext(), list);
    bannerViewPager.setAdapter(lunBoAdapter);

    initDoc();

    // Show somewhere in the middle 
    bannerViewPager.setCurrentItem(list.size() * 10000);

    // Use handler Automatic carousel 
    handler.sendEmptyMessageDelayed(0, time * 1000);

    // Listening Events for State Change 
    bannerViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
      @Override
      public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

      }

      @Override
      public void onPageSelected(int position) {
        // When selecting a certain 1 Page time , Toggle the background of small dots 
        for (int i = 0; i < listDoc.size(); i++) {
          if (position % listDoc.size() == i) {
            listDoc.get(i).setBackgroundResource(R.drawable.shape_01);
          } else {
            listDoc.get(i).setBackgroundResource(R.drawable.shape_02);
          }
        }


      }

      @Override
      public void onPageScrollStateChanged(int state) {

      }
    });


  }

  /**
   *  Initialize dot 
   */
  private void initDoc() {

    // Create 1 Set of , Record these little dots 
    listDoc = new ArrayList<>();
    // Empty the layout 
    linearBannner.removeAllViews();

    for (int i = 0; i < list.size(); i++) {

      ImageView docImage = new ImageView(getContext());
      if (i == 0) {
        docImage.setBackgroundResource(R.drawable.shape_01);
      } else {
        docImage.setBackgroundResource(R.drawable.shape_02);
      }

      // Add to Collection 
      listDoc.add(docImage);

      // Add to Linear Layout 
      LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

      params.setMargins(5, 0, 5, 0);

      linearBannner.addView(docImage, params);


    }


  }

  /**
   *  Provide carousel time to the outside world 
   */
  public void setTimeSecond(int time) {
    this.time = time;
  }

  /**
   *  Click event 
   *
   * @param onClickLisner
   */
  public void setClickListner(OnClickLisner onClickLisner) {

    this.onClickLisner = onClickLisner;
  }

  private class LunBoAdapter extends PagerAdapter {

    private List<String> list;
    private Context context;

    public LunBoAdapter(Context context, List<String> list) {
      this.context = context;
      this.list = list;
    }

    @Override
    public int getCount() {
      return Integer.MAX_VALUE;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
      return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {

      // Create imageView
      ImageView imageView = new ImageView(context);
      imageView.setScaleType(ImageView.ScaleType.FIT_XY);
      // Load this picture 
      Glide.with(context).load(list.get(position % list.size())).into(imageView);


      // Click event 
      imageView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
          // Trigger 
          onClickLisner.onItemClick(position % list.size());
        }
      });

      // Touch event 
      imageView.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

          switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
              // Cancel handler Messages and callbacks on the body 
              handler.removeCallbacksAndMessages(null);

              break;
            case MotionEvent.ACTION_MOVE:
              handler.removeCallbacksAndMessages(null);
              break;
            case MotionEvent.ACTION_CANCEL:
              handler.sendEmptyMessageDelayed(0, time * 1000);
              break;
            case MotionEvent.ACTION_UP:
              handler.sendEmptyMessageDelayed(0, time * 1000);
              break;
          }

          return false;
        }
      });

      // Add to Container 
      container.addView(imageView);

      // Return 

      return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {

      container.removeView((View) object);
    }
  }

  public interface OnClickLisner {
    void onItemClick(int position);
  }
}

Custom dots


public class CountView extends View implements View.OnClickListener {

  private int count = 0;

  public CountView(Context context) {
    super(context);
    init();
  }


  public CountView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    init();
  }

  public CountView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
  }

  // Method of initialization 
  private void init() {

    this.setOnClickListener(this);
  }

  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    Paint paint = new Paint();
    paint.setColor(Color.RED);
    paint.setAntiAlias(true);
    paint.setStyle(Paint.Style.FILL);

    // Circle 
    canvas.drawCircle(300,300,200,paint);


    paint.setColor(Color.BLACK);
    paint.setTextSize(100);

    String text = String.valueOf(count);

    // Get the width and height of the text 
    Rect rect = new Rect();
    paint.getTextBounds(text,0,text.length(),rect);

    canvas.drawText(text,300-rect.width()/2,300+rect.height()/2,paint);

  }

  @Override
  public void onClick(View view) {
    count ++;

    // Redraw 
    postInvalidate();
  }
}

Small dot shape


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

  <solid android:color="#00ff00"/>

  <corners android:radius="10dp"/>

  <size android:height="10dp" android:width="10dp"/>


</shape>

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

  <solid android:color="#ff0000"/>

  <corners android:radius="10dp"/>

  <size android:height="10dp" android:width="10dp"/>


</shape>

Running in Main


public class MainActivity extends AppCompatActivity {

  private CustomBanner customBanner;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    customBanner = findViewById(R.id.custom_banner);

    getDataFromNet();
  }

  private void getDataFromNet() {

    OkHttpUtil.doGet("https://www.zhaoapi.cn/ad/getAd", new Callback() {

      private List<String> list;

      @Override
      public void onFailure(Call call, IOException e) {

      }

      @Override
      public void onResponse(Call call, Response response) throws IOException {
        if (response.isSuccessful()){
          String json = response.body().string();

          final HomeBean detalBean = new Gson().fromJson(json,HomeBean.class);

          list = new ArrayList<>();
          List<HomeBean.DataBean> data = detalBean.getData();

          for (int i = 0; i < data.size(); i++) {
            String icon = data.get(i).getIcon();
            list.add(icon);
          }

          runOnUiThread(new Runnable() {
            @Override
            public void run() {
              // Setting time 
              customBanner.setTimeSecond(5);

              // Set up display carousel 
              customBanner.setImageUrls(list);

              //banner Events on the click jump details page of 
    banner.setOnBannerListener(new OnBannerListener() {
      @Override
      public void OnBannerClick(int position) {

        List<ShouBean.DataBean> datab = shouBean.getData();

        if (datab.get(position).getType() == 0) {
          Intent intent = new Intent(getActivity(), WebViewActivity.class);
          intent.putExtra("databurl", datab.get(position).getUrl());
          startActivity(intent);
        } else {
          Toast.makeText(getContext(), " You are about to jump to the Product Details page ", Toast.LENGTH_SHORT).show();
        }
      }
    });

            }
          });

        }
      }
    });

  }
}

WebView page


public class WebViewActivity extends AppCompatActivity {

  private WebView web_view;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web_view);

    web_view = findViewById(R.id.web_view);

    String databurl = getIntent().getStringExtra("databurl");

    web_view.loadUrl(databurl);

    //webview1 Series settings 
    web_view.setWebViewClient(new WebViewClient());// Open in the current application , Instead of going to the browser 
    WebSettings settings = web_view.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
  }
}


Related articles: