android:theme 与 setTheme()设置透明效果并不同

若是想将Activity设置为透明的,我们首先想到的做法是在AndroidMainfest.xml中使用android:theme设置透明主题:

android:name=".activity.internat.TestActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.Translucent.NoTitleBar"/>

运行一下,发现确实起作用了,很好。

在实际情况是,这个Activity在某个条件下需要设置成透明的,另外条件下需要是正常显示内容的,这时候就需要动态设置主题了,所谓的动态就是能够根据条件状态选择当前所使用的主题,sdk中有个方法

setTheme()

然后,在onCreate()方法中进行判断:

boolean isNeedTransparent= ...//根据实际情况判断
if(isNeedTransparent){
    setTheme(android.R.style.Theme_Translucent_NoTitleBar);
}else{
    setTheme(R.style.common); //自定义的非透明的主题
}

AndroidMainfest.xml中设置的是默认主题(自定义非透明的主题):

android:name=".activity.internat.TestActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:theme="@style/common"/>

运行后,发现设置透明主题没有起作用,背景是黑色的。

这种情况,网上有几个说法,若是想setTheme在onCreate方法中起到作用,有一下几种方法:
(1)setTheme需要写在super.onCreate()前面

setTheme(...);
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);

(2)setTheme需要写在super.onCreate()与setContentView()中间

super.onCreate(savedInstanceState);
setTheme(...);
setContentView(R.layout.my_layout);

(3)setTheme写在setContentView()后面

经过本人亲测,以上三种方法都是不起作用的。
所以若想使用setTheme设置透明效果,在onCreate中不用折腾了,不管怎么都是不起作用,不起作用,不起作用!(重要的事情说三遍)

难道就没有办法动态设置透明效果了吗?当然是有的,推荐以下两种方法:

(1)直接在AndroidMainfest.xml设置透明主题

android:name=".activity.internat.TestActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.Translucent.NoTitleBar"/>

对,这种方式Activity只能是透明效果,不能达到根据某个条件动态判断选择主题的目的。

(2)AndroidMainfest.xml+Override setTheme()方式
思路是在AndroidMainfest.xml设置一个默认主题,然后在Activity中重写setTheme()方法,动态改变theme,代码如下。

android:name=".activity.internat.TestActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.Translucent.NoTitleBar"/>
//在Activity中重写setTheme方法
@Override
public void setTheme(int resid) {
   Bundle bundle = this.getIntent().getExtras();
   boolean isNeedTransparent= bundle.getBoolean("NeedTransparent");
   if(isNeedTransparent){
            super.setTheme(android.R.style.Theme_Translucent_NoTitleBar);
    }else{
        super.setTheme(R.style.common);
    }
}

需要注意的是:
AndroidMainfest.xml设置的默认主题必须是Theme.Translucent.NoTitleBar,若是设置为自定义主题,然后在setTheme()中再设置为Theme.Translucent.NoTitleBar不起作用

需要重写setTheme()方法,经过debug发现,进入Activity之后,是先调用了setTheme(),然后才调用onCreate(),所以就不要再onCreate中折腾了。

你可能感兴趣的:(android)