AutoBannerpackage com.bwie.autobanner; import android.content.Context; import android.graphics.Bitmap; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache; import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator; import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer; import com.nostra13.universalimageloader.core.download.BaseImageDownloader; import com.nostra13.universalimageloader.utils.StorageUtils; import java.io.File; import java.util.ArrayList; import java.util.List; public class AutoBanner extends FrameLayout { private ViewPager viewPager; private LinearLayout linearLayout; private List<String> list; private int time = 2; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 0) { //viewPager显示下一页 viewPager.setCurrentItem(viewPager.getCurrentItem() + 1); //再次发送延时消息 handler.sendEmptyMessageDelayed(0, time * 1000); } } }; private ArrayList<ImageView> images; private OnBannerClickListner bannerClickListner; public AutoBanner(@NonNull Context context) { super(context); init(); } public AutoBanner(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public AutoBanner(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } /** * 对外提供设置时间 */ public void setTimeSeconds(int time) { this.time = time; } /** * 初始化的方法,,,加载布局 */ private void init() { //初始化imageLoader ImageLoaderUtil.init(getContext()); View view = View.inflate(getContext(), R.layout.custom_banner_layout, this); //找到控件 viewPager = view.findViewById(R.id.view_pager); linearLayout = view.findViewById(R.id.linear_layout); } /** * 对外提供设置数据的方法 */ public void setImageUrl(List<String> list) { this.list = list; if (list == null) { return; } //设置适配器 MyAdapter myAdapter = new MyAdapter(getContext(), list); //设置适配器 viewPager.setAdapter(myAdapter); initDoc(list); //2.手动的可以无限滑动 viewPager.setCurrentItem(list.size() * 100000);//设置当前展示中间某个足够大的位置 handler.sendEmptyMessageDelayed(0, time * 1000);//发送一个延时的空消息 //viewPage设置监听事件 viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } /** * 当选中某个页面的时候,把当前的小圆点背景变成绿色 * @param position */ @Override public void onPageSelected(int position) { for (int i = 0; i < images.size(); i++) { if (i == position % images.size()) { images.get(i).setImageResource(R.drawable.shape_01); } else { images.get(i).setImageResource(R.drawable.shape_02); } } } @Override public void onPageScrollStateChanged(int state) { } }); } /** * 动态添加小圆点 * * @param list */ private void initDoc(List<String> list) { //1.需要一个集合记录一下小圆点的imageView控件 images = new ArrayList<ImageView>(); //2...linearLayout上面的视图清空一下再去添加 linearLayout.removeAllViews(); for (int i = 0; i < list.size(); i++) { ImageView imageView = new ImageView(getContext()); if (i == 0) { imageView.setImageResource(R.drawable.shape_01); } else { imageView.setImageResource(R.drawable.shape_02); } //添加到集合去 images.add(imageView); //添加到线性布局上 //这是布局参数,,刚开始小圆点之间没有距离,所以使用java代码指定宽度高度,并且指定小圆点之间的距离 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.setMargins(5, 0, 5, 0); linearLayout.addView(imageView, params); } } private class MyAdapter extends PagerAdapter { Context context; List<String> list; public MyAdapter(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; } /** * viewPager具有预加载,默认的前后加载一页,,,默认的容器里面最多三页 * * @param container * @param position * @return */ @Override public Object instantiateItem(ViewGroup container, final int position) { //1.把这个当前展示的视图添加到容器中...container ImageView imageView = new ImageView(context); //..........使图片平铺整个imageView控件 imageView.setScaleType(ImageView.ScaleType.FIT_XY); //imageLoader加载图片到这个imageView控件上 ImageLoader.getInstance().displayImage(list.get(position % list.size()), imageView, ImageLoaderUtil.getDefaultOption()); //给imageView设置触摸的监听事件 imageView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { int action = motionEvent.getAction();//获取手指的动作 switch (action) { case MotionEvent.ACTION_DOWN://按下的动作...应该取消发送消息的操作 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; } }); imageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { bannerClickListner.onBannerClick(position % list.size()); } }); container.addView(imageView);//添加到容器 //2.把当前展示的视图返回 return imageView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { //销毁视图 container.removeView((View) object); } } private static class ImageLoaderUtil { /** * 初始化 * * @param context */ public static void init(Context context) { File cacheDir = StorageUtils.getCacheDirectory(context); //缓存文件夹路径 ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context) .threadPoolSize(3) // default 线程池内加载的数量 .threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级 .tasksProcessingOrder(QueueProcessingType.FIFO) // default .denyCacheImageMultipleSizesInMemory() .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //可以通过自己的内存缓存实现 .memoryCacheSize(2 * 1024 * 1024) // 内存缓存的最大值 .memoryCacheSizePercentage(13) // default .diskCache(new UnlimitedDiskCache(cacheDir)) // default 可以自定义缓存路径 .diskCacheSize(50 * 1024 * 1024) // 50 Mb sd卡(本地)缓存的最大值 .diskCacheFileCount(100) // 可以缓存的文件数量 // default为使用HASHCODE对UIL进行加密命名, 还可以用MD5(new Md5FileNameGenerator())加密 .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) .imageDownloader(new BaseImageDownloader(context)) // default .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default .writeDebugLogs() // 打印debug log .build(); //开始构建 //关键初始化的代码 ImageLoader.getInstance().init(config); } public static DisplayImageOptions getDefaultOption() { DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.mipmap.ic_launcher) // 设置图片下载期间显示的图片 .showImageForEmptyUri(R.mipmap.ic_launcher) // 设置图片Uri为空或是错误的时候显示的图片 .showImageOnFail(R.mipmap.ic_launcher) // 设置图片加载或解码过程中发生错误显示的图片 .resetViewBeforeLoading(true) // default 设置图片在加载前是否重置、复位 .cacheInMemory(true) // default 设置下载的图片是否缓存在内存中 .cacheOnDisk(true) // default 设置下载的图片是否缓存在SD卡中 .considerExifParams(true) // default .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default 设置图片以如何的编码方式显示 .bitmapConfig(Bitmap.Config.ARGB_8888) // default 设置图片的解码类型 .displayer(new SimpleBitmapDisplayer()) // default 还可以设置圆角图片new RoundedBitmapDisplayer(20) .build(); return options; } } public void setOnBannerClickListner(OnBannerClickListner bannerClickListner) { this.bannerClickListner = bannerClickListner; } /** * 点击的接口 */ public interface OnBannerClickListner { public void onBannerClick(int position); } }_____________________________________________________________________________MainActivity
package com.bwie.autobanner; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Toast; import com.google.gson.Gson; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity { private int time = 100; private AutoBanner customBanner; private List<String> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); customBanner = (AutoBanner) findViewById(R.id.custom_bannner); customBanner.setTimeSeconds(3); getDataFromNet(); } private void getDataFromNet() { //http://120.27.23.105/ad/getAd //1.创建一个okhttp客户端对象 OkHttpClient okHttpClient = new OkHttpClient(); //2.通过请求的构建器来创建一个请求对象,并指定请求的url地址 Request request = new Request.Builder() .url("http://120.27.23.105/ad/getAd") .build(); //3.客户端调用请求 Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, final Response response) throws IOException { if (response.isSuccessful()) { final String string = response.body().string();//耗时,子线程获取 runOnUiThread(new Runnable() {//主线程 @Override public void run() { Log.i("---+++", string); BannerBean bannerBean = new Gson().fromJson(string, BannerBean.class); final List<BannerBean.DataBean> data = bannerBean.getData(); list = new ArrayList<>(); for (int i = 0; i < data.size(); i++) { list.add(data.get(i).getIcon()); } customBanner.setImageUrl(list); //设置点击事件 customBanner.setOnBannerClickListner(new AutoBanner.OnBannerClickListner() { @Override public void onBannerClick(int position) { //Toast.makeText(MainActivity.this,"点击了",Toast.LENGTH_SHORT).show(); //判断 BannerBean.DataBean dataBean = data.get(position); if (dataBean.getType() == 0) {//跳转到详情 Intent intent = new Intent(MainActivity.this, SecondActivity.class); intent.putExtra("url", dataBean.getUrl()); startActivity(intent); } else if (dataBean.getType() == 1) { Toast.makeText(MainActivity.this, "我要跳转到商品详情页", Toast.LENGTH_SHORT).show(); } } }); } }); } } }); } // // /** // * C.请求权限的结果....可以获取到用户是否允许了权限 // */ // @TargetApi(23) // @Override // public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { // super.onRequestPermissionsResult(requestCode, permissions, grantResults); // if (requestCode == 1001) { // //grantResults用户允许权限的返回值....数组里面放的是用户是否允许权限 // //PackageManager.PERMISSION_GRANTED允许权限 // if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // getDataFromNet(); // } else { // Toast.makeText(MainActivity.this, "拒绝", Toast.LENGTH_SHORT).show(); // } // } // } }___________--____________--------------------------------------------------------------------SecondActivity
package com.bwie.autobanner; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); String url = getIntent().getStringExtra("url"); WebView webView = (WebView) findViewById(R.id.web_view); webView.loadUrl(url); webView.setWebViewClient(new WebViewClient()); WebSettings settings = webView.getSettings(); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setJavaScriptEnabled(true); } }________-----------------------------------------
布局<com.bwie.autobanner.AutoBanner android:id="@+id/custom_bannner" android:layout_width="match_parent" android:layout_height="wrap_content"/>____________--------------------------------------------------------------<WebView android:id="@+id/web_view" android:layout_width="match_parent" android:layout_height="match_parent"> </WebView>
-----------------------------------------------------------------------<android.support.v4.view.ViewPager android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="200dp"> </android.support.v4.view.ViewPager> <LinearLayout android:id="@+id/linear_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/view_pager" android:layout_centerHorizontal="true" android:layout_marginBottom="10dp" android:orientation="horizontal">---------------------------------------------------------------------------
小圆点
1<?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:width="10dp" android:height="10dp"/> </shape> 2<?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:width="10dp" android:height="10dp"/> </shape>
自定义轮播imageLayout
最新推荐文章于 2024-09-03 09:19:32 发布