gpt4 book ai didi

java - Android SDK,从 URL 设置 ImageView 位图

转载 作者:行者123 更新时间:2023-12-01 21:40:11 24 4
gpt4 key购买 nike

如何将 url 中的图像放入 ImageView 中?

我不想使用任何库,我宁愿坚持使用简单的旧方式,我喜欢它。不要评判我。就像我在让这个工作之前说过的那样,但奇怪的是它不再工作了

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ImageView damnit = (ImageView)findViewById(R.id.imageview);
try {
URL url = new URL("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png");

InputStream in = url.openStream();
Bitmap bitt = BitmapFactory.decodeStream(in);
damnit.setImageBitmap(bitt);
} catch (Exception e) {
e.printStackTrace();
}
}

编辑!

我真是个白痴,很抱歉花了你们的时间...我必须有一个 runOnUI 线程,并且里面有“damnit.setImageBitmap(bitt);”

最佳答案

您正在尝试从主线程获取 URL。这是不可能的。这是您将收到的错误:android.os.NetworkOnMainThreadException

尝试使用 AsyncTask 例如从 URL 检索图像。

@Override
public void onCreate() {
super.onCreate();

ImageView damnit = (ImageView)findViewById(R.id.imageview);
DownloadTask downloadTask = new DownloadTask(damnit);
downloadTask.execute();
}

class DownloadTask extends AsyncTask <Void, Void, Bitmap>{
private ImageView imageView;

public DownloadTask(ImageView imageView) {
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(Void... params) {
try {
URL url = new URL("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png");
InputStream in = url.openStream();
return BitmapFactory.decodeStream(in);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
}
<小时/>

或者使用库,例如​​ Glide :

如何设置 Glide:

构建.gradle:

repositories {
mavenCentral() // jcenter() works as well because it pulls from Maven Central
}

dependencies {
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.android.support:support-v4:19.1.0'
}

创建时:

Glide.with(this)
.load("https://www.some-url.com/image.jpg")
.into(imageView);

关于java - Android SDK,从 URL 设置 ImageView 位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36592810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com