Java 我想在每次打开android活动时设置随机背景。。我试过这种方法,但是失败了

Java 我想在每次打开android活动时设置随机背景。。我试过这种方法,但是失败了,java,android,android-layout,Java,Android,Android Layout,在下面的代码中,我将图像ID传递给数组 我想在每次打开活动时设置背景随机图像 public class StickyHome extends Activity { int[] imageIds = {R.drawable.sticky, R.drawable.sticky1, R.drawable.sticky2, R.drawable.sticky3, R.drawable.sticky4

在下面的代码中,我将图像ID传递给数组

我想在每次打开活动时设置背景随机图像

public class StickyHome extends Activity {

    int[] imageIds = {R.drawable.sticky,
            R.drawable.sticky1,
            R.drawable.sticky2,
            R.drawable.sticky3,
            R.drawable.sticky4,
            R.drawable.sticky5,
            R.drawable.sticky6,
            R.drawable.sticky7};


    RelativeLayout layout = (RelativeLayout)findViewById(R.id.colourSticky);
    Random genorator = new Random();
    int randomImageId =imageIds[genorator.nextInt(imageIds.length)];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        layout.setBackgroundResource(randomImageId);
        setContentView(R.layout.activity_sticky_home);
}
}

在创建活动之前,也在设置内容视图之前,您试图查找dviewbyd

int[] imageIds = {R.drawable.sticky,
        R.drawable.sticky1,
        R.drawable.sticky2,
        R.drawable.sticky3,
        R.drawable.sticky4,
        R.drawable.sticky5,
        R.drawable.sticky6,
        R.drawable.sticky7
};


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_sticky_home);

    RelativeLayout layout = (RelativeLayout)findViewById(R.id.colourSticky);
    Random genorator = new Random();
    int randomImageId =imageIds[genorator.nextInt(imageIds.length)];
    layout.setBackgroundResource(randomImageId);

}

您试图在初始化布局之前获取对布局的引用

setContentView(R.layout.activity\u sticky\u home)之后使用以下代码方法

layout = (RelativeLayout)findViewById(R.id.colourSticky);
您应该在
setContentView()
方法之后使用对布局对象的任何引用

layout = (RelativeLayout)findViewById(R.id.colourSticky);
您还应该只按如下方式设置类变量声明

RelativeLayout layout;

上面的代码片段是正确的。但请注意,应用程序崩溃的原因是,即使在创建
活动之前,调用
findViewById
。请注意,如果尚未调用
setContentView
,则
findViewById
将返回
NULL