<pre>
package com.yourname.pro;
import android.content.Context;
import android.graphics.Point;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.yourname.pro.R;
import cn.bingoogolapple.bgabanner.BGABanner;
public class BGABannerAdapter implements BGABanner.Adapter<ImageView, String> {
private Context context;
//设置图片宽高比
float scale = (float) 750 / (float) 320;
int screenWidth;
public BGABannerAdapter(Context context) {
this.context = context;
this.screenWidth = getScreenWidth();
}
private int getScreenWidth(){
//获取屏幕的宽度
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Point size = new Point();
wm.getDefaultDisplay().getSize(size);
screenWidth = size.x;
System.out.println("screenWidth:" + screenWidth);
return screenWidth;
}
@Override
public void fillBannerItem(final BGABanner banner, final ImageView itemView, String model, int position) {
System.out.println("fillBannerItem() running");
//计算BGABanner的应有高度
int viewHeight = Math.round(screenWidth / scale);
//设置BGABanner的宽高属性
ViewGroup.LayoutParams banner_params = banner.getLayoutParams();
banner_params.width = screenWidth;
banner_params.height = viewHeight;
banner.setLayoutParams(banner_params);
//此处使用的是glide的override函数直接设置图片尺寸
Glide.with(context)
.load(model)
.placeholder(R.mipmap.banner_holder)
.override(banner_params.width,banner_params.height)
.into(itemView);
}
}
</pre>
优化为只获取一次屏幕宽度,避免fillBannerItem()函数里面多次调用。