Android自定义Banner轮播效果
作者:wrpbk
这篇文章主要为大家详细介绍了Android自定义Banner轮播效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了Android自定义Banner轮播效果展示的具体代码,供大家参考,具体内容如下
自定义View布局
<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>
自定义View主体内容
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); //再次发送 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(); } /** * 初始化 */ private void init() { View view = View.inflate(getContext(), R.layout.bannner_layout, this); ButterKnife.bind(this, view); } /** * 对外提供设置image路径的方法 */ public void setImageUrls(List<String> list) { this.list = list; if (list == null) { return; } //设置适配器 LunBoAdapter lunBoAdapter = new LunBoAdapter(getContext(), list); bannerViewPager.setAdapter(lunBoAdapter); initDoc(); //显示中间某个位置 bannerViewPager.setCurrentItem(list.size() * 10000); //使用handler自动轮播 handler.sendEmptyMessageDelayed(0, time * 1000); //状态改变的监听事件 bannerViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { //在选中某一页的时候,切换小圆点的背景 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) { } }); } /** * 初始化小圆点 */ private void initDoc() { //创建一个集合,记录这些小圆点 listDoc = new ArrayList<>(); //清空布局 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); } //添加到集合 listDoc.add(docImage); //添加到线性布局 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.setMargins(5, 0, 5, 0); linearBannner.addView(docImage, params); } } /** * 对外提供轮播的时间 */ public void setTimeSecond(int time) { this.time = time; } /** * 点击事件 * * @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) { //创建imageView ImageView imageView = new ImageView(context); imageView.setScaleType(ImageView.ScaleType.FIT_XY); //加载这张图片 Glide.with(context).load(list.get(position % list.size())).into(imageView); //点击事件 imageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { //触发 onClickLisner.onItemClick(position % list.size()); } }); //触摸事件 imageView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { switch (motionEvent.getAction()) { case MotionEvent.ACTION_DOWN: //取消handler身上的消息和回调 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; } }); //添加到容器 container.addView(imageView); //返回 return imageView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } } public interface OnClickLisner { void onItemClick(int position); } }
自定义小圆点
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(); } //初始化的方法 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); //圆 canvas.drawCircle(300,300,200,paint); paint.setColor(Color.BLACK); paint.setTextSize(100); String text = String.valueOf(count); //拿到文本的宽度和高度 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 ++; //重新绘制 postInvalidate(); } }
小圆点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>
在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() { //设置时间 customBanner.setTimeSecond(5); //设置显示轮播 customBanner.setImageUrls(list); //banner的点击跳转详情页面的事件 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(), "即将跳转到商品详情页面", Toast.LENGTH_SHORT).show(); } } }); } }); } } }); } }
WebView页面
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); //webview一系列设置 web_view.setWebViewClient(new WebViewClient());//在当前应用打开,而不是去浏览器 WebSettings settings = web_view.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。