1. 程式人生 > >輪播圖的兩種方法

輪播圖的兩種方法

依賴
implementation ‘com.android.support:design:27.1.1’
implementation ‘com.nostra13.universalimageloader:universal-image-loader:1.9.5’
implementation ‘com.google.code.gson:gson:2.8.5’
implementation project(’:xListView’)
compile ‘com.youth.banner:banner:1.4.10’

activity_banner

<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout xmlns:android=“

http://schemas.android.com/apk/res/android
android:layout_width=“match_parent”
android:layout_height=“match_parent”
xmlns:app=“http://schemas.android.com/apk/res-auto”>

<com.youth.banner.Banner
    android:id="@+id/banner"
    android:layout_width="0dp"
    android:layout_height="200dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:indicator_width="8dp"
    app:indicator_height="8dp"
    app:indicator_drawable_selected="@drawable/shape_sel_dot"
    app:indicator_drawable_unselected="@drawable/shape_normal_dot"
    />

</android.support.constraint.ConstraintLayout>

activity_main

<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout
xmlns:android=“http://schemas.android.com/apk/res/android
xmlns:tools=“http://schemas.android.com/tools
android:layout_width=“match_parent”
android:layout_height=“match_parent”
xmlns:app=“

http://schemas.android.com/apk/res-auto
tools:context=".MainActivity">

<android.support.v4.view.ViewPager
    android:layout_width="0dp"
    android:layout_height="200dp"
    android:id="@+id/banner"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    ></android.support.v4.view.ViewPager>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:orientation="horizontal"
    android:padding="8dp"
    android:id="@+id/dots"
    app:layout_constraintRight_toRightOf="@+id/banner"
    app:layout_constraintBottom_toBottomOf="@+id/banner"
    ></LinearLayout>


<TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:id="@+id/desc"
    android:ellipsize="end"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintBottom_toBottomOf="@id/banner"
    app:layout_constraintRight_toLeftOf="@id/dots"
    />

<me.maxwin.view.XListView
    android:id="@+id/xListView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintTop_toBottomOf="@+id/banner"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    ></me.maxwin.view.XListView>

</android.support.constraint.ConstraintLayout>

activity_second

<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout xmlns:android=“http://schemas.android.com/apk/res/android
android:layout_width=“match_parent”
android:layout_height=“150dp”
xmlns:app=“http://schemas.android.com/apk/res-auto”>

<ImageView
    android:layout_width="140dp"
    android:layout_height="140dp"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    android:id="@+id/imageurl"
    />

<TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="text"
    app:layout_constraintTop_toTopOf="@+id/imageurl"
    app:layout_constraintRight_toLeftOf="@+id/imageurl"
    app:layout_constraintLeft_toLeftOf="parent"
    android:id="@+id/title"
    />

<TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="text"
    app:layout_constraintBottom_toBottomOf="@+id/imageurl"
    app:layout_constraintRight_toLeftOf="@+id/imageurl"
    app:layout_constraintLeft_toLeftOf="parent"
    android:id="@+id/summary"
    />

</android.support.constraint.ConstraintLayout>

App

public class App extends Application {

@Override
public void onCreate() {
    super.onCreate();


    ImageLoader.getInstance().init(
            new ImageLoaderConfiguration.Builder(this)
             .memoryCacheSizePercentage(10)
            .diskCacheSize(50*1024*1024)
            .defaultDisplayImageOptions(
                    new DisplayImageOptions.Builder()
                    .showImageOnFail(R.mipmap.ic_launcher)
                    .showImageOnLoading(R.mipmap.ic_launcher)
                    .cacheInMemory(true)
                    .cacheOnDisk(true)
                    .build()
            )
            .build()
    );

}

}

NetUtil

public class NetUtil {

//介面
public  interface  CallBack<T> {
      void getdata(T t);
}

//非同步任務
public static void  yibu(String lujing, final Class clazz, final CallBack callBack){

    new AsyncTask<String, Void, Object>() {

        @Override
        protected Object doInBackground(String... strings) {
            return NetUtil.jiexi(strings[0],clazz);
        }

        @Override
        protected void onPostExecute(Object o) {
              callBack.getdata(o);
        }
    }.execute(lujing);

}

//網路解析
private static <T> T jiexi(String lujing, Class clazz) {

  T t = (T) new Gson().fromJson(NetUtil.geturl(lujing),clazz);
    return t;
}

//網路請求
public static String geturl(String lujing){
    String result="";
    try {
        //定義地址
        URL url=new URL(lujing);
        //開啟連線
        HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();
        //請求方法
        urlConnection.setRequestMethod("GET");
        //讀取超時
        urlConnection.setReadTimeout(5000);
        //連線超時
        urlConnection.setConnectTimeout(5000);
        if (urlConnection.getResponseCode()==200){
            result = NetUtil.zifu(urlConnection.getInputStream());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

private static String zifu(InputStream inputStream) throws IOException {


          StringBuilder builder =new StringBuilder();



  BufferedReader br =  new BufferedReader(new InputStreamReader(inputStream));

  for(String tmp = br.readLine(); tmp != null ; tmp = br.readLine() ){



      builder.append(tmp);
  }

    return builder.toString();
}

}

BannerAdapter

public class BannerAdapter extends PagerAdapter {

private List<BannerResponse.Banner> mDatas;
private Context context;


public BannerAdapter(Context context) {
    this.context = context;
    mDatas = new ArrayList<>();


}

@Override
public int getCount() {
    return mDatas.size() > 0 ? 5000 : 0;
}

public BannerResponse.Banner getItem(int position) {
    return mDatas.get(position % mDatas.size());
}


public void setmDatas(List <BannerResponse.Banner> datas) {
    mDatas.clear();
    if(datas != null) {
          mDatas.addAll(datas);
    }

    notifyDataSetChanged();

}




@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {

    return  view == object;
}

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

  ImageView imageView = new ImageView(context);
   imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
   container.addView(imageView);
    ImageLoader.getInstance().displayImage(getItem(position).getPicUrl(),imageView);

    return imageView;
}

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

    container.removeView((View) object);
}

}

BannerActivity

public class BannerActivity extends AppCompatActivity {

private Banner banner;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_banner);

    banner = findViewById(R.id.banner);

    //設定banner樣式
    banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
    //設定圖片載入器
    banner.setImageLoader(new ImageLoaderInterface<ImageView>() {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            BannerResponse.Banner banner = (BannerResponse.Banner) path;
            com.nostra13.universalimageloader.core.ImageLoader.getInstance()
                    .displayImage(banner.getPicUrl(), imageView);
        }

        @Override
        public ImageView createImageView(Context context) {
            ImageView imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }
    });

    initData();
}

private void initData() {
    NetUtil.yibu("https://api.tianapi.com/wxnew/?key=c4aa776e0a51d57d6750511e2baa46b6&num=6&page=1", BannerResponse.class, new NetUtil.CallBack<BannerResponse>() {
        @Override
        public void getdata(BannerResponse o) {
            //設定圖片集合
            banner.setImages(o.getNewslist());
            banner.setBannerTitles(getTitles(o));
            //banner設定方法全部呼叫完畢時最後呼叫
            banner.start();
        }
    });
}

private List<String> getTitles(BannerResponse bannerResponse) {
    List<String> result = new ArrayList<>();
    for (BannerResponse.Banner banner: bannerResponse.getNewslist()) {
        result.add(banner.getTitle());
    }
    return result;
}

}

MainActivity

public class MainActivity extends AppCompatActivity {

private ViewPager banner;
private TextView desc;
private LinearLayout dots;
private BannerAdapter adapter;

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


    banner = findViewById(R.id.banner);
    desc = findViewById(R.id.desc);
    dots = findViewById(R.id.dots);

    adapter = new BannerAdapter(this);
    banner.setAdapter(adapter);

    banner.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        //快取的點
        private int cacheIndex = -1;

        //頁面滾動
        @Override
        public void onPageScrolled(int i, float v, int i1) {

        }

        //頁面選擇
        @Override
        public void onPageSelected(int i) {
            //改變檔案
            desc.setText(adapter.getItem(i).getTitle());
            //改變當前點
            dots.getChildAt(i % dots.getChildCount()).setSelected(true);

            //還原原來的點
            if (cacheIndex >= 0) {
                dots.getChildAt(cacheIndex % dots.getChildCount()).setSelected(false);
            }
            cacheIndex = i;
        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });

    initData();
}

private void initData() {
    NetUtil.yibu("https://api.tianapi.com/wxnew/?key=c4aa776e0a51d57d6750511e2baa46b6&num=6&page=1"
            , BannerResponse.class, new NetUtil.CallBack<BannerResponse>() {
                @Override
                public void getdata(BannerResponse bannerResponse) {
                    if (bannerResponse == null || !bannerResponse.isSuccess()) {
                        Toast.makeText(MainActivity.this, "請求錯誤", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    adapter. setmDatas(bannerResponse.getNewslist());
                    initDot(bannerResponse.getNewslist().size());

                    //切換到中間
                    int center = adapter.getCount() / 2;
                    center = center - center % bannerResponse.getNewslist().size();
                    banner.setCurrentItem(center);

                    //開啟輪播
                    startlooper();
                }
            });
}


private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        banner.setCurrentItem(banner.getCurrentItem() + 1);
        mHandler.sendEmptyMessageDelayed(0, 2000);
    }
};

private void startlooper() {
    mHandler.removeMessages(0);
    mHandler.sendEmptyMessageDelayed(0, 2000);
}

//初始化小圓點
private void initDot(int size) {
    dots.removeAllViews();
    for (int i = 0; i < size; i++) {
        ImageView imageView = new ImageView(this);
        imageView.setBackgroundResource(R.drawable.selector_dot);
        //佈局引數: 寬高包裹  左右8dp
        LinearLayout.LayoutParams params =
                new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
        int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
        params.leftMargin = margin;
        params.rightMargin = margin;
        dots.addView(imageView, params);
    }
}

}