Android 轮播图--自定义轮播界面样式
百度关键字“轮播图”可以搜到各种各样的文章和实现方法。简单的轮播效果随手就来,这篇文章之后我会一直更新,直到自己可以游刃有余的实现各种炫酷的UI为止。
我们常说:有轮子为啥要自己造轮子。但是用别人写好的轮子,自己也要吃透它,不然如何应对UI设计师。
github上有好多写好的框架,结合自己的需求和排行,我选用了ConvenientBanner。
先放效果图:
第一步,集成:
在app build.gradle中添加:implementation'com.bigkoo:ConvenientBanner:2.1.4'
第二步,activity_main.xml中添加控件,以及自定义item布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="200dp">
<ImageView
android:id="@+id/bg_img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
<com.bigkoo.convenientbanner.ConvenientBanner
android:id="@+id/convenientBanner"
android:layout_width="match_parent"
android:layout_height="200dp"
app:canLoop="true" />
</RelativeLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.myapplication4.ClipRoundImageView
android:id="@+id/item_img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="30dp"
android:scaleType="centerCrop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:radius="10dp" />
</android.support.constraint.ConstraintLayout>
上面布局中用到的RoundImageView,顺便也贴出来,两种方法都发出来,可根据自己喜好选择
package com.example.myapplication4;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.os.Build;
import androidx.appcompat.widget.AppCompatImageView;
import android.util.AttributeSet;
import android.view.View;
public class ClipRoundImageView extends AppCompatImageView {
private int width;
private int height;
private Path path;
private int defaultRadius = 0;
private int radius;
private int leftTopRadius;
private int rightTopRadius;
private int rightBottomRadius;
private int leftBottomRadius;
public ClipRoundImageView(Context context) {
this(context,null);
}
public ClipRoundImageView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public ClipRoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
if (Build.VERSION.SDK_INT < 18) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
// 读取配置
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.Custom_Round_Image_View);
radius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_radius, defaultRadius);
leftTopRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_left_top_radius, defaultRadius);
rightTopRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_right_top_radius, defaultRadius);
rightBottomRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_right_bottom_radius, defaultRadius);
leftBottomRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_left_bottom_radius, defaultRadius);
//如果四个角的值没有设置,那么就使用通用的radius的值。
if (defaultRadius == leftTopRadius) {
leftTopRadius = radius;
}
if (defaultRadius == rightTopRadius) {
rightTopRadius = radius;
}
if (defaultRadius == rightBottomRadius) {
rightBottomRadius = radius;
}
if (defaultRadius == leftBottomRadius) {
leftBottomRadius = radius;
}
array.recycle();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
width = getWidth();
height = getHeight();
}
@Override
protected void onDraw(Canvas canvas) {
path = new Path();
int maxLeft = Math.max(leftTopRadius, leftBottomRadius);
int maxRight = Math.max(rightTopRadius, rightBottomRadius);
int minWidth = maxLeft + maxRight;
int maxTop = Math.max(leftTopRadius, rightTopRadius);
int maxBottom = Math.max(leftBottomRadius, rightBottomRadius);
int minHeight = maxTop + maxBottom;
if (width >= minWidth && height > minHeight) {
Path path = new Path();
//四个圆角
path.moveTo(leftTopRadius, 0);
path.lineTo(width - rightTopRadius, 0);
path.quadTo(width, 0, width, rightTopRadius);
path.lineTo(width, height - rightBottomRadius);
path.quadTo(width, height, width - rightBottomRadius, height);
path.lineTo(leftBottomRadius, height);
path.quadTo(0, height, 0, height - leftBottomRadius);
path.lineTo(0, leftTopRadius);
path.quadTo(0, 0, leftTopRadius, 0);
canvas.clipPath(path);
}
super.onDraw(canvas);
}
}
package com.example.myapplication4;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;
@SuppressLint("AppCompatCustomView")
public class RoundImageView extends AppCompatImageView {
private int mBorderRadius = 60;
private Paint mPaint;
private Matrix matrix;
private BitmapShader mBitmapShader;
public RoundImageView(Context context) {
this(context,null);
}
public RoundImageView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
matrix = new Matrix();
mPaint = new Paint();
mPaint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
if(null == getDrawable()){
return;
}
Bitmap bitmap = drawableToBitamp(getDrawable());
mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
float scale = 1.0f;
if(!(bitmap.getWidth() == getWidth() && bitmap.getHeight() == getHeight())) {
// 如果图片的宽或者高与view的宽高不匹配,计算出需要缩放的比例;缩放后的图片的宽高,一定要大于我们view的宽高;所以我们这里取大值;
scale = Math.max(getWidth() * 1.0f / bitmap.getWidth(), getHeight() * 1.0f / bitmap.getHeight());
}
matrix.setScale(scale,scale);
mBitmapShader.setLocalMatrix(matrix);
canvas.drawRoundRect(new RectF(0,0, getWidth(), getHeight()), mBorderRadius,mBorderRadius,mPaint);
super.onDraw(canvas);
}
private Bitmap drawableToBitamp(Drawable drawable){
if(drawable instanceof BitmapDrawable){
BitmapDrawable bd = (BitmapDrawable) drawable;
return bd.getBitmap();
}
//当设置不为图片时,即为颜色时,获取控件的宽度
int w = drawable.getIntrinsicWidth() <= 0 ? getWidth() : drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight() <= 0 ? getHeight() : drawable.getIntrinsicHeight();
Bitmap bitmap = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0,0, w, h);
drawable.draw(canvas);
return bitmap;
}
}
接下来就是MainActivity中的Java代码实现了
package com.example.myapplication4;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private ImageView bgImg;
private ConvenientBanner convenientBanner;
private List<Integer> localImages = new ArrayList<Integer>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
localImages.add(R.mipmap.chengxi);
localImages.add(R.mipmap.jinping);
localImages.add(R.mipmap.qilihe);
bgImg = findViewById(R.id.bg_img);
Glide.with(MainActivity.this)
.load("http://www.pptbz.com/pptpic/UploadFiles_6909/201203/2012031220134655.jpg")
.into(bgImg);
convenientBanner = findViewById(R.id.convenientBanner);
convenientBanner.setPages(new CBViewHolderCreator() {
@Override
public Holder createHolder(View itemView) {
return new LocalImageHolderView(itemView);
}
@Override
public int getLayoutId() {
return R.layout.item_localimage;
}
}, localImages);
//设置两个点图片作为翻页指示器,不设置则没有指示器,可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
convenientBanner.setPageIndicator(new int[]{R.drawable.unseclect_dot, R.drawable.seclect_dot});
convenientBanner.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
convenientBanner.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(int position) {
Toast.makeText(MainActivity.this, "点击了第" + position + "个图片", Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onResume() {
super.onResume();
convenientBanner.startTurning();
}
@Override
protected void onPause() {
super.onPause();
convenientBanner.stopTurning();
}
class LocalImageHolderView extends Holder<Integer> {
private ClipRoundImageView imageView;
public LocalImageHolderView(View itemView) {
super(itemView);
}
@Override
protected void initView(View itemView) {
imageView = itemView.findViewById(R.id.item_img);
}
@Override
public void updateUI(Integer data) {
imageView.setImageResource(data);
}
}
attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Custom_Round_Image_View">
<attr name="radius" format="dimension"/>
<attr name="left_top_radius" format="dimension"/>
<attr name="right_top_radius" format="dimension"/>
<attr name="right_bottom_radius" format="dimension"/>
<attr name="left_bottom_radius" format="dimension"/>
</declare-styleable>
</resources>
}
最后: 两个小圆点是自己画的unseclect_dot.xml, seclect_dot.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#333333" />
<size android:height="5dp" android:width="5dp"/>
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#cccccc" />
<size android:height="5dp" android:width="5dp"/>
</shape>
待续......