[英]Android Studio Java: How do I set the background of a constraint layout to be an image from a URL?
我正在開發一個應用程序,它要求我將背景圖像更改為 URL 在不同時間提供的圖像。 但是我該怎么做呢? 使用以下方法不起作用,因為該方法采用 integer 而不是字符串。
layout.setBackgroundResource(URL);
我也不能使用 Picasso 庫中的以下方法,因為無法將約束布局轉換為目標:
Picasso.get().load(URL).into((Target) theLayout);
我也試過這樣做:
try {
String pictureURL = URL;
Drawable fromURL = Drawable.createFromStream(((InputStream) new URL(pictureURL).openStream()), null);
layout.setBackground(fromURL);
} catch(Exception j) {
errorView.setText(j.getMessage() + "Why there");
}
但是,我的 try catch 是捕獲錯誤而不是讓它工作。
我能做什么? 請注意,我不想只將來自 URL 的圖片設置為 ImageView 的背景。我想將圖片設置為整個屏幕的背景。
您必須嘗試將此代碼合並到您的項目中。 使用Glide Android
activity.java
中。java classGlide.with(this).load(Uri.parse("https://your_image_url/example.png")).into(new CustomTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
layout.setBackground(resource); // here you will set your background..
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
不要忘記在manifest.xml
中添加 Inte.net 權限或一些代碼。
<manifest
...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true">
...
</application>
</manifest>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.