package com.example.pei.recyclerviewdemo;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
/**
* Created by
*/
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.ViewHolder>{
int a[] = {
R.mipmap.d,
R.mipmap.e,
R.mipmap.f,
R.mipmap.d,
R.mipmap.e,
R.mipmap.f,
R.mipmap.d,
R.mipmap.e,
R.mipmap.f
};
Context mContext;
public RVAdapter(Context context) {
mContext = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_image,null);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.mImageView.setImageResource(a[position]);
holder.mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("RVAdapter", "position:..." + position);
}
});
ViewGroup.LayoutParams params = holder.mImageView.getLayoutParams();
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(),a[position]);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
//拿到屏幕宽
int screenWidth = ((Activity) holder.mImageView.getContext())
.getWindowManager().getDefaultDisplay().getWidth();
float aaa = (float)screenWidth/3;
//图片压缩比例
float bili = (float) (width/aaa);
params.height = (int) (height/bili);
params.width = (int) (width/bili);
holder.mImageView.setLayoutParams(params);
}
@Override
public int getItemCount() {
return a.length;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView mImageView;
public ViewHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.image_main);
}
}
}
为了防止以瀑布流显示图片的时候,图片会有空白区域.
本来以为会出现特殊情况导致一列的图片超过其他列图片高度太多,后来发现不会发生,recycleview已经考虑到了这个.nice
item的position不会因为recycleview的自动排列而乱了数组中的位置