Android应用动态修改主题


1.使用API设置主题

如下所示,在Activity中使用setTheme

setTheme(R.style.MyTheme1);

2.调用API的时机

需要在super.onCreate(savedInstanceState)之前调用setTheme

3.重新设置主题

要重新设置主题,则需要结束Activity,重新启动才可以

public class MainActivity extends Activity {

    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        if(MyApplication.SHOW_THEME_FLAG == MyApplication.SHOW_1_THEME_FLAG){
            setTheme(R.style.MyTheme2);
        }else if(MyApplication.SHOW_THEME_FLAG == MyApplication.SHOW_2_THEME_FLAG){
            setTheme(R.style.MyTheme1);
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = findViewById(R.id.tv);

        getActionBar().show();
        getActionBar().setTitle("ActionBar Title");

        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(MyApplication.SHOW_THEME_FLAG == MyApplication.SHOW_1_THEME_FLAG){
                    MyApplication.SHOW_THEME_FLAG = MyApplication.SHOW_2_THEME_FLAG;
                }else if(MyApplication.SHOW_THEME_FLAG == MyApplication.SHOW_2_THEME_FLAG){
                    MyApplication.SHOW_THEME_FLAG = MyApplication.SHOW_1_THEME_FLAG;
                }

                Intent mIntent = getIntent();
                finish();
                overridePendingTransition(0,0);
                startActivity(mIntent);
            }
        });
    }}

4.常用主题style设置

    <style name="MyTheme1" parent="@android:style/Theme.Material">
        <item name="android:colorPrimaryDark">#f00<item name="android:colorPrimary">#ff0<item name="android:windowBackground">@color/windowBackgroundColor1<item name="android:navigationBarColor">#0000ffstyle>

    <style name="MyTheme2" parent="@android:style/Theme.Material">
        <item name="android:colorPrimaryDark">#757575<item name="android:colorPrimary">#03A9F4<item name="android:windowBackground">@color/windowBackgroundColor2<item name="android:navigationBarColor">#1976D2style>

               

上一篇:给 IDEA 换个酷炫的主题吧,这个有点哇塞啊!


下一篇:前端换肤的N种方案,请收下