First create 2 class one is your Activity and other one is a singleton class having a String type of variable .
Below is the code for Singleton class (DataManager) :
Now add a button in your Activity and on click on that button, open gallery to select image to set as background using below code :
And add onActivityResult that will get after user select image from gallery. Use below code :
This will get url of image that user has selected and save that url in the form of string in DatManger class (Singleton class that we have created above).
Now we need to set this image as the background. Let’s suppose you are using LinearLayout as the parent layout of Activity. In onCreate method use findViewById to Initialize LinearLayout on which you need to set image as background.
Now in onCreate method after initializing LinearLayout use below code to set the image path as background :
Now what will happen when first time user open that Activity it will show default image as we have done in if statement in above code as DataManager’s imageUrl is blank. Now when user selects image from Gallery, our code will initialize DataManager’s imageUrl with the selected image’s path. After that we are recreating the same Activity by again opening the same Activity. After this again our above code will get executed but this time it will not get DataManager’s imageUrl as blank and will have url of image. In this case we are setting that image url as the background of LinearLayout.
Note : This will work until user closes the application. Because we are using Singleton class to store the selected image’s Url . And once app is closed all objects are destroyed. If you want this to work everytime when application is opened then use SharedPreferences(Preferred and Light Weight) or SQLite Database.
Leave a Reply