android - 方法 getWindow().setBackgroundDrawableResource(int resid) 在 onCreate() 之外不起作用

标签 android

这是我的应用程序的简短草图

...
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.start);

    ... //at this place, getWindow().setBackgroundDrawableResource(int resid)
        //would work perfectly

    mainView();

}

void mainView() {
   setContentView(R.layout.main);

   ...

   if (...) {
     getWindow().setBackgroundDrawableResource(R.drawable.anyDrawable);
   }

   ...

}

但在 mainView() 中,该方法不会产生任何影响。并且没有异常被抛出。

main.xml 已经定义了背景图像,但 start.xml 没有定义。这会导致我的问题吗?

或者我可以用其他方式更改背景图片吗?

最佳答案

PS 你不能多次设置内容 View ,你应该做的是在布局中有一个 ID 像 main 这样的父 View ,然后使用

findViewById(R.id.main).setBackgroundDrawableResource(R.drawable.anyDrawable);

并且在xml布局中你需要设置你想设置的 View 的id(这应该是最顶层的 View )

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dip" 
    android:id="@+id/main"></LinearLayout>

将 id 添加到 View 后,您需要保存布局并构建项目

如果您想发布您的 xml 代码以及您的布局名称,我可以为您编写更多内容

关于android - 方法 getWindow().setBackgroundDrawableResource(int resid) 在 onCreate() 之外不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10933179/

相关文章:

android - 如何在 Android Things 上请求权限?

java - 实时文本输入解析android键盘

android - Google Map Directions Api 无法执行路线/路径请求

javascript - 当移动设备从 sleep 中唤醒时重新加载网页

Android Retrofit POST 请求缓存

android - 添加用于特定任务的新依赖配置

android - Cordova 窗口错误 : An error occurred while listing Android targets

android - 从 phonegap plugin-webIntent 开始 Activity

android - 如何在 android 中以编程方式配置 Launcher Activity ?

android - 如何将datePicker的值设置到EditText中?