Search code examples
javaandroidtimeandroid-drawablelocaltime

How to change background with day/night time?


In my application I want to change background with Day/Night time.
My mean is I want check time if time is night set night background from drawable and when time is Day set day background from drawable.

Sorry for my bad question, I am an amateur and really need your help.
How can I do it in android?


Solution

  • You can use a code something like this, by specifying the hours you consider in morning and the hours you consider as night.

    I considered the time from 06:00 - 18:00 as morning and 18:00 - 05:00 as night. Change it accordingly.

       Calendar calendar = Calendar.getInstance();
       int time = c.get(Calendar.HOUR_OF_DAY);
    
        if(time >= 6 && time < 18){
    
        image.setImageResource(R.drawable.morning);     
    
         }else if (time >= 18 && time < 6){
    
        image.setImageResource(R.drawable.night);
    
        }
    

    EDIT

    As suggested by @AxelH, it would be better to just specify either one of the time (morning or night only). The code would be something like:

    Calendar calendar = Calendar.getInstance();
       int time = c.get(Calendar.HOUR_OF_DAY);
    
        if(time >= 6 && time < 18){
    
        image.setImageResource(R.drawable.morning);     
    
         }else{
    
        image.setImageResource(R.drawable.night);
    
        }