我想在每次打开我的android活动时设置随机背景.我试过这种方法,但被撞坏了



在下面的代码中,我将图像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);
}
}

在创建活动之前,以及在设置内容视图之前,您试图查找ViewById。

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);
}

您试图在初始化layout之前获取对它的引用。

setContentView(R.layout.activity_sticky_home);方法之后使用以下代码。

layout = (RelativeLayout)findViewById(R.id.colourSticky);

应该在setContentView()方法之后使用对布局对象的任何引用。

您还应该仅按如下方式设置类变量声明。

RelativeLayout layout;

上面的代码段是正确的。但请注意,您的应用程序崩溃的原因是,您甚至在创建Activity之前就调用了findViewById。请注意,如果您还没有调用setContentViewfindViewById将返回NULL

最新更新