1.声明 GridView
private PullToRefreshGridView ptrgv;
2.为 GridView 添加图片
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder vh;
if (view == null) {
view = LayoutInflater.from(ctx).inflate(R.layout.list_item_for_gridview, null);
vh = new ViewHolder();
vh.iv = (ImageView) view.findViewById(R.id.imageView_cen);
view.setTag(vh);
}
vh = (ViewHolder) view.getTag();
Picture pic = pictures.get(i);
//用OkhttpUtils compile 'com.zhy:okhttputils:2.6.2'
final ViewHolder finalVh = vh;
OkHttpUtils
.get()
.url("https://www.baidu.com/img/bd_logo1.png")
.build()
.execute(new BitmapCallback() {
@Override
public void onError(okhttp3.Call call, Exception e, int id) {
}
@Override
public void onResponse(Bitmap response, int id) {
finalVh.iv.setImageBitmap(response);
}
});
return view;
}
static class ViewHolder {
ImageView iv;
public ImageView getIv() {
return iv;
}
}
3.为 GridView 设置点击事件
ptrgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
imageView = (ImageView) findViewById(R.id.imageView_cen);
Toast.makeText(MainActivity.this,"jaja",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this,ItemLayout.class);
byte[] mypic = null;
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
mypic = Bitmap2Bytes(bitmap);
intent.putExtra("picture",mypic);
startActivity(intent);
}
});
4.将 Bitmap 转换为 Bytes
private byte[] Bitmap2Bytes(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100,byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
5.设置另一个 Activity
public class ItemLayout extends AppCompatActivity {
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_layout);
imageView = (ImageView) findViewById(R.id.imageview33);
Intent intent = getIntent();
if(intent != null){
byte [] mypics = intent.getByteArrayExtra("picture");
Bitmap bitmap = BitmapFactory.decodeByteArray(mypics,0,mypics.length);
imageView.setImageBitmap(bitmap);
}
}
private byte[] Bitmap2Bytes(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100,byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
}
6.另一个 Avtivity 的 Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView_cen"/>
</LinearLayout>