在Android程序里显示网络图片

以下是一个使用OkHttp请求网络图片显示Android程序示例: 1. 添加依赖 在你的`build.gradle`文件中添加以下依赖: ``` implementation 'com.squareup.okhttp3:okhttp:4.9.1' implementation 'com.squareup.picasso:picasso:2.71828' ``` 2. 请求网络图片 在你的Activity或Fragment中,使用以下代码请求网络图片并将其显示在ImageView中: ``` OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://www.example.com/image.jpg") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { final Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream()); // 更新UI runOnUiThread(new Runnable() { @Override public void run() { ImageView imageView = findViewById(R.id.imageView); imageView.setImageBitmap(bitmap); } }); } else { throw new IOException("Unexpected code " + response); } } }); ``` 3. 使用Picasso简化代码 你也可以使用Picasso来简化代码。它是一个强大的图片加载库,可以从URL、文件或资源加载图片,并在ImageView中显示它们。 添加依赖后,你只需要使用以下代码即可加载图片: ``` Picasso.get().load("https://www.example.com/image.jpg").into(imageView); ``` 这将使用OkHttp来请求网络图片,并将其显示在ImageView中。Picasso还提供其他功能,如调整大小、缓存和转换。你可以查看官方文档了解更多信息:https://square.github.io/picasso/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值