Android 、切换主题的实现

通过重启Activity,调用setTheme()方法设置相应的Theme来实现的。

1. 定义两套主题

attrs.xml定义

<resources>
    <attr name="main_bg" format="reference|color"/>
    <attr name="main_textcolor" format="reference|color"/>
    <attr name="second_bg" format="reference|color"/>
    <attr name="second_textcolor" format="reference|color"/>
resources>

style.xml定义

  

    

在layout中使用主题

layout/main.xml

"http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?attr/main_bg"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    "?attr/main_textcolor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    

2. 设置主题

Activity的设置主题的方式
public void setTheme (int resid)

Set the base theme for this context. Note that this should be called before any views are instantiated in the Context (for example before calling setContentView(View) or inflate(int, ViewGroup)).

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(SharedPreferencesMgr.getInt("theme", 0) == 1) {
            setTheme(R.style.theme_2);
        } else {
            setTheme(R.style.theme_1);
        }

        .....
        setContentView(R.layout.activity_main);
        btn = (Button)findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SharedPreferencesMgr.getInt("theme", 0) == 1) {
                    SharedPreferencesMgr.setInt("theme", 0);
                    setTheme(R.style.theme_1);
                } else {
                    SharedPreferencesMgr.setInt("theme", 1);
                    setTheme(R.style.theme_2);
                }
                changeTheme();
            }
        });

        .....
    }

3. 重启Activity

1)  api>=11
```
public void recreate ()

Added in API level 11
Cause this Activity to be recreated with a new instance. This results in essentially the same flow as when the Activity is created due to a configuration change -- the current instance will go through its lifecycle to onDestroy() and a new instance then created after it.

```

2) api<11
    finish();
    startActivity(getIntent());
public void changeTheme(){
        if(Build.VERSION.SDK_INT < 11)
        {
            finish();
            startActivity(getIntent());
        }else{
            recreate();
        }
    }

4.其他实现方式

还有一种切换主题方式,虽然效果稍好一点(主题无缝切换),因为比较繁琐,个人不太喜欢.以上部分代码来自这个项目,喜欢的可以自行查看.
https://github.com/dersoncheng/MultipleTheme

你可能感兴趣的:(android)