简体   繁体   English

在活动启动时更改线性布局背景图像

[英]Change Linear layout background image on activity startup

I change Linear Layout background image via this code: 我通过以下代码更改“线性布局”背景图片:

mainlayout.setBackgroundResource(R.drawable.back);

But i want do this on every time that activity starts, In first start and switching between activities. 但是我想在每次活动开始时都执行此操作,首先是在活动之间进行切换。 I put this code inside an IF statement in onCreate() but background not change! 我将此代码放在onCreate()的IF语句中,但背景没有改变! Of course when i set this code to a button works fine! 当然,当我将此代码设置为按钮时,效果很好! How and where i have to put my code? 如何以及在哪里放置代码?

my complete code is: 我完整的代码是:

            //check theme id
    if(myDbHelper.gettheme()==1)
    {
        mainlayout.setBackgroundResource(R.drawable.back);
    }else if(myDbHelper.gettheme()==2)
    {
        mainlayout.setBackgroundResource(R.drawable.blueback);
    }

You need to put your code into the onResume() method. 您需要将代码放入onResume()方法中。

Here are details that will explain why http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle 以下是详细信息,这些内容将说明为什么http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

您可能要参考Android活动生命周期 ,但我建议使用onResume()方法。

EDIT: Are you sure theme is either 1 or 2? 编辑:您确定主题是1或2?

If you want to do it everytime, why don't you just define it as mainLayout's background in your layout.xml? 如果您想每次都做,为什么不在layout.xml中将它定义为mainLayout的背景呢? Otherwise, use onResume() rather than onCreate(). 否则,请使用onResume()而不是onCreate()。

I'm assuming based off your code snippet you have the image you want as a background as a drawable resource already in project. 我假设基于您的代码片段,您已经将想要作为背景的图像作为项目中已经存在的可绘制资源。 If so you could just go into the XML and add into the linerayout: 如果是这样,您可以进入XML并添加到linerayout中:

android:background="@drawable/back"

This should just set the background within the XML layout avoiding having to have code set it within one of the activity life-cycle functions. 这应该只是在XML布局中设置背景,而不必在活动生命周期功能之一中进行代码设置。

Though in the case you wanted different themes as I just saw in the original post (seemed to be edited since I was typing this up), you could try storing the constant int of the R.drawable that the user wants as the background or theme, and have your DB Helper's getTheme() return that reference to set the background without the if statements. 虽然在您想要不同的主题的情况下(就像我在原始帖子中看到的那样(自从我键入内容以来似乎已被编辑)),您可以尝试存储用户想要的R.drawable的常量int作为背景或主题,并让您的数据库助手的getTheme()返回该引用以设置背景,而无需if语句。

Such saying the user changes their preference to R.drawable.black or .blueback store the int within the DB so it get return by gettheme rather than a 1 or 2 enumeration. 这样一来,用户将其偏好设置更改为R.drawable.black或.blueback即可将int存储在DB中,以便它通过gettheme而不是1或2枚举获得返回。 Not sure if this would be a best practice though. 不确定这是否是最佳做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM