繁体   English   中英

Android Studio Java:如何将约束布局的背景设置为来自 URL 的图像?

[英]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

  1. 在您的项目中实施Glide
  2. 将此代码写到您的activity.java中。java class
Glide.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM