1

I want to change the background of a fragment based on the time of the day (light for day, dark for night). Right now, I hard coded the background image in the fragment's layout:

android:background="@drawable/weatherbg"

But to have a dynamic background, I assume that I have to do that in the fragment activity class, inside the onCreate method? I'm not sure how though, since you cannot use setContentView in fragments.
I know I have to write some conditional code, but not sure what's the method to set the background image inside a fragment.

This is my first experience with Android, and any help is greatly appreciated.

IngridX
  • 93
  • 4
  • did you want to implement dark mode? – Jimale Abdi Oct 27 '19 at 03:19
  • @JimaleAbdi Hi, no I do not want to implement dark mode, I'm just trying to have a day/night background because the page displays the weather forecast. – IngridX Oct 27 '19 at 03:38
  • OK I think you have one drawable for day and one for night if that's yes it's easy to implement but detecting whether is day or night it needs some attention – Jimale Abdi Oct 27 '19 at 03:52
  • @JimaleAbdi yes, but how do I call the drawable/set the background in my activity? Right now I set it in the layout xml but I don't think you can have a conditional statement there (?) (like ```if day: background="@drawable/day"``` ) – IngridX Oct 27 '19 at 04:30

1 Answers1

0

you can change background by using setBackgroundResource(), but you must give id for your View

RelativeLayout rl;    

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


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

fro detect whether is day or night you can use this free API also look this

Jimale Abdi
  • 2,574
  • 5
  • 26
  • 33
  • Thanks! However I did the following in my weather fragment and it did not work: ```public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_weather, container, false); view.setBackgroundResource(R.drawable.weatherbg);``` Might it be that in my styles.xml, I set a theme for the whole app? Do I need smt extra to override that? Thanks again for your help. – IngridX Oct 27 '19 at 05:21
  • if you are using fragment refer [this](https://stackoverflow.com/questions/11692162/android-change-background-color-of-fragment) – Jimale Abdi Oct 27 '19 at 05:56