【问题标题】:Change activity background dynamically [closed]动态更改活动背景[关闭]
【发布时间】:2016-07-20 06:57:32
【问题描述】:

我正在开发一个天气应用程序,我希望根据天气的变化(如从白天到晚上或从白天到晚上)来更改我的活动背景。我似乎无法找到答案。 一点帮助将不胜感激。

【问题讨论】:

  • 在您的自定义 Drawable 类中绘制所有内容
  • pskink,你能详细说明一下吗?
  • 制作一个自定义的Drawable 类,并通过 callimg View#setBackground 在任何视图中使用它
  • psink,很抱歉再次打扰你,我是新来的,你能给我一个链接吗?

标签: android android-studio


【解决方案1】:

试试这个:

final int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
layout.setBackgroundDrawable( getResources().getDrawable(R.drawable.yourimg));
} else {
layout.setBackground(R.drawable.yourimg);
}

【讨论】:

  • 你测试layout.setBackground(R.drawable.yourimg);了吗? setBackground 期望 Drawable,而不是 int 参数
  • 它确实有效,但我自己做了一些修改。干杯
  • 如果您觉得我们的帮助很有价值,请将问题标记为已解决;)
  • 很高兴为您提供帮助。对于 getDrawable(int),它已被弃用。
  • 嗨@Cyborg91 你能把我的回答标记为接受吗?干杯
【解决方案2】:

将此添加到您的活动中onCreate()

protected void onCreate(Bundle savedInstanceState) {

    //...
    Calendar cal = Calendar.getInstance();
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    boolean isNight = hour < 6 || hour > 18;

    int currentDrawable = isNight ? R.drawable.night : R.drawable.day;
    View decorView = getWindow().getDecorView();
    Drawable drawable = ContextCompat.getDrawable(this, currentDrawable);
    if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
        decorView.setBackgroundDrawable(drawable);
    else
        decorView.setBackground(drawable);
}      

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 2023-04-08
    • 2013-10-19
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    相关资源
    最近更新 更多