android - Android fragment 中的动态背景

标签 android android-studio android-layout android-fragments

我想根据一天中的时间更改 fragment 的背景(白天亮,晚上暗)。现在,我在 fragment 的布局中硬编码了背景图像:

android:background="@drawable/weatherbg"

但是要拥有动态背景,我假设我必须在 fragment Activity 类中的 onCreate 方法中这样做吗? 我不确定如何,因为您不能在 fragment 中使用 setContentView。
我知道我必须编写一些条件代码,但不确定在 fragment 中设置背景图像的方法是什么。

这是我第一次使用 Android,非常感谢任何帮助。

最佳答案

您可以使用setBackgroundResource() 更改背景,但您必须为您的View提供id

RelativeLayout rl;    

 rl = (RelativeLayout)findViewById(R.id.relativeLayout1); // the id of the view


 rl.setBackgroundResource(R.drawable.day_image); // change the background

fro检测是白天还是晚上可以用this免费的API也看this

关于android - Android fragment 中的动态背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58576361/

相关文章:

android - 连接不同类型的可观察对象

android - 在 Android 中使用 Google Books API

android - 如何在 Eclipse 中使用 Maven 导入 Android AAR 依赖项?

AndroidStudio 上不显示 AndroidTest 文件夹

android - 如何防止 C++ 重新编译 Android NDK 中的所有文件?

android - 可滚动的 TextView 不允许在应用程序暂停后选择文本

android - 如何使用从客户那里收到的 keystore 对 APK 进行签名?

java - 检索商品价格时 Android 应用内结算崩溃

android - 对于通过 FragmentTransaction 添加的 fragment ,fitsSystemWindows 效果消失了

android - 如何在代码中更改 ListView 中一项的背景