Erayzer Erayzer - 4 years ago 150
Android Question

Android - Custom background image

I want to change my app's background randomly. It's supposed to have a random image from its own folder as background. It works perfectly with some devices but with some of them doesn't. I wonder what could cause this inconsistency. Here is my random background generator class:

public class arkaplanGenerator {
public static int arkaplan(){
int sonucArkaplan = 0;
Random r = new Random();
int sayi = r.nextInt(11);
switch (sayi){
case 0:
sonucArkaplan = R.drawable.bavaria;
break;
case 1:
sonucArkaplan = R.drawable.gorges;
break;
case 2:
sonucArkaplan = R.drawable.more;
break;
case 3:
sonucArkaplan = R.drawable.mountains;
break;
case 4:
sonucArkaplan = R.drawable.pisa;
break;
case 5:
sonucArkaplan = R.drawable.sea;
break;
case 6:
sonucArkaplan = R.drawable.sunset;
break;
case 7:
sonucArkaplan = R.drawable.sunset2;
break;
case 8:
sonucArkaplan = R.drawable.wai;
break;
case 9:
sonucArkaplan = R.drawable.water;
break;
case 10:
sonucArkaplan = R.drawable.waterfall;
break;
}
return sonucArkaplan;
}


And here is how i use it in my main activity:

LinearLayout linearLayout = (LinearLayout)findViewById(R.id.activity_main);
linearLayout.setBackground(getResources().getDrawable(arkaplanGenerator.arkaplan()));


Those images are in drawable folder.Thanks in advance.

Answer Source

The method getDrawable from the Resources class has been deprecated. You should use the one from ContextCompat:

linearLayout.setBackground(ContextCompat.getDrawable(getApplicationContext(),arkaplanGenerator.arkaplan()));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download