Android - 自定义背景图片

Android - Custom background image

我想随机更改我的应用程序的背景。它应该有一个来自它自己的文件夹的随机图像作为背景。它与某些设备完美配合,但其中一些则不然。我想知道是什么导致了这种不一致。这是我的随机背景生成器 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;
}

下面是我在主程序中使用它的方式 activity:

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

这些图像提前folder.Thanks可绘制。

Resources class 中的 getDrawable 方法已被弃用。您应该使用 ContextCompat:

中的那个
linearLayout.setBackground(ContextCompat.getDrawable(getApplicationContext(),arkaplanGenerator.arkaplan()));