我正在创建一个应用程序,我想要更改完整应用程序的主题。即如果我点击任何Button
说更改主题,它应该更改主题w.r.t Application
Context
。
我试过
OnClickListener onClick = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
getApplicationContext().setTheme(R.style.AppTheme1);
setContentView(R.layout.activity_main);
}
};
但这并没有反映出来。是否需要进行任何修改以便我可以更改Application
Themes
添加styles.xml
<style name="AppBaseTheme" parent="android:Theme.Light">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
<item name="android:textColor">#ffffff</item>
</style>
<style name="AppTheme1" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
<item name="android:textColor">#000000</item>
</style>
答案 0 :(得分:0)
java如下
Utils.java
import android.app.Activity;
import android.content.Intent;
public class Utils
{
private static int sTheme;
public final static int THEME_DEFAULT = 0;
public final static int THEME_WHITE = 1;
public final static int THEME_BLUE = 2;
/**
* Set the theme of the Activity, and restart it by creating a new Activity of the same type.
*/
public static void changeToTheme(Activity activity, int theme)
{
sTheme = theme;
activity.finish();
activity.startActivity(new Intent(activity, activity.getClass()));
}
/** Set the theme of the activity, according to the configuration. */
public static void onActivityCreateSetTheme(Activity activity)
{
switch (sTheme)
{
default:
case THEME_DEFAULT:
activity.setTheme(R.style.FirstTheme);
break;
case THEME_WHITE:
activity.setTheme(R.style.SecondTheme);
break;
case THEME_BLUE:
activity.setTheme(R.style.Thirdheme);
break;
}
}
}
并按如下方式使用
Utils.changeToTheme(this, Utils.THEME_WHITE);
您可以按如下方式编写点击事件
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.button1:
Utils.changeToTheme(this, Utils.THEME_DEFAULT);
break;
case R.id.button2:
Utils.changeToTheme(this, Utils.THEME_WHITE);
break;
case R.id.button3:
Utils.changeToTheme(this, Utils.THEME_BLUE);
break;
}
}
您可以拥有如下主题样式
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="FirstTheme" >
<item name="android:textColor">#FF0000</item>
</style>
<style name="SecondTheme" >
<item name="android:textColor">#00FF00</item>
</style>
<style name="Thirdheme" >
<item name="android:textColor">#0000F0</item>
</style>
</resources>
有关完整示例,请访问http://mrbool.com/how-to-change-the-layout-theme-of-an-android-application/25837