我在styles.xml中定义了两个主题:
<style name="AppTheme" parent="android:Theme.Holo"></style>
<style name="AppLightTheme" parent="android:Theme.Holo.Light">
<item name="android:background">#FFFFFF</item>
</style>
这是我设置活动主题的方式:
protected void changeTheme(boolean dark) {
if (dark) {
setTheme(R.style.AppTheme);
} else {
setTheme(R.style.AppLightTheme);
}
}
现在我更改主题后,只有背景保持不变直到我打开不同的布局并返回。我使用DrawerLayout,所以我基本上在布局之间切换。
如何重新绘制或刷新它?
这是我尝试过的并没有做任何事情的事情:
ViewGroup vg = findViewById (R.id.mainLayout);
vg.invalidate();
Intent intent = getIntent(); //this one is obvious, had to include so you don't try this unnecesarry.. code
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
getWindow().getDecorView().findViewById(android.R.id.content).invalidate();
getWindow().getDecorView().findViewById(android.R.id.content).refreshDrawableState();
getWindow().getDecorView().findViewById(android.R.id.content).requestLayout();
findViewById(android.R.id.content).invalidate();
myLayout.invalidate();
有什么想法吗?
答案 0 :(得分:4)
您可以致电recreate()重新创建活动,并使用新主题重新创建所有视图。
protected void changeTheme(boolean dark) {
if (dark) {
setTheme(R.style.AppTheme);
} else {
setTheme(R.style.AppLightTheme);
}
recreate();
}
答案 1 :(得分:0)
recreate()即可。 当需要重新启动活动时,您可以使用以下代码。
Bundle temp_bundle = new Bundle();
onSaveInstanceState(temp_bundle);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("bundle", temp_bundle);
startActivity(intent);
finish();
并在onCreate ......
@Override
public void onCreate(Bundle savedInstanceState) {
if (getIntent().hasExtra("bundle") && savedInstanceState==null){
savedInstanceState = getIntent().getExtras().getBundle("bundle");
}
//add code for theme
switch(theme)
{
case LIGHT:
setTheme(R.style.LightTheme);
theme = LIGHT;
break;
case BLACK:
setTheme(R.style.BlackTheme);
theme = BLACK;
break;
default:
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//code
}
我已经包含了切换主题的代码。在这里,&#39;主题&#39;是一个字符串变量。