1

I am developing a weather app where I wish to change my activity background as the weather changes like night to day or day to night.I seemed unable to find answers. A little help would be deeply appreciated.

hemen
  • 1,460
  • 2
  • 16
  • 35

2 Answers2

1

Try this:

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);
}
ashxvi
  • 144
  • 1
  • 10
1

Add this in your Activity 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);
}      

Hope this helps!!

Gueorgui Obregon
  • 5,077
  • 3
  • 33
  • 57