(待完善)Android应用换肤 更换主题

主要有以下的步骤:

  • 在 attrs.xml资源文件中定义自己的属性:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="appBg" format="reference" />
</resources>
  • 在styles.xml资源文件中定义几种主题风格:
<resources>
    <style name="theme1">
        <item name="appBg">@color/login_btn_color1</item>
    </style>

    <style name="theme2">
        <item name="appBg">@color/login_btn_color2</item>
    </style>
</resources>
  • 在Activity中的onCreate()函数中的setContentView()之前动态设置主题,一定要在setContentView()函数之前设置setTheme()啊:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        mContext = this;
        super.onCreate(savedInstanceState);
        setTheme(getIntent().getIntExtra("theme_res", R.style.theme1));
        setContentView(R.layout.activity_main);
}

//R.layout.activity_main 布局文件中需要定制主题的组件进行如下设置(android:background:):
      <Button
          android:layout_width="220px"
           android:layout_height="70px"
           android:id="@+id/login"
           android:text="登录"
           android:textColor="#FFFFFF"
           android:textSize="20px"
           android:gravity="center"
           android:layout_marginTop="15px"
           android:layout_alignParentLeft="true"
           android:layout_alignParentBottom="true"
           android:layout_below="@+id/layout_login"
           android:background="?attr/appBg" />
  • 在需要更换主题的时候,进行重新启动该Acticvity,并且把先前的Activity销毁掉:
    @OnClick(R.id.changeTheme1)
    public void onChangeTheme1Click() {
        changeTheme(R.style.theme1);
    }

    @OnClick(R.id.changeTheme2)
    public void onChangeTheme2Click() {
        changeTheme(R.style.theme2);
    }

    //注意要设置Intent.FLAG_ACTIVITY_CLEAR_TOP 
    //Intent.FLAG_ACTIVITY_NEW_TASK  这两个标志位
    private void changeTheme(int resId) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("theme_res", resId);
        startActivity(intent);
    }
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容