Android - 如何重新扩展视图层次结构
我在使我的 Activity 响应主题更改时遇到问题(即 Theme_Dark 更改为 Theme_Light)。
在 Activity 中,下面的代码运行良好,并且在创建 Activity 时更改主题(方法 getPreferenceTheme() 仅获取通过 PreferenceActivity 设置的主题首选项值)。
protected void onCreate(Bundle savedInstanceState) {
setTheme(getPreferenceTheme());
super.onCreate(savedInstanceState);
setContentView(R.layout.controls);
}
但如何动态更改主题呢?那么,在我更改 PreferenceActivity 中的主题并返回主 Activity 后,如何才能更改它呢?
我知道我可以重新启动 Activity 来执行此操作(再次调用 onCreate()),但我不想这样做,并且听说可以在 onResume() 中“重新膨胀视图层次结构” - 我该怎么做?
我尝试了以下方法(在黑暗中刺伤),但没有任何乐趣。
protected void onResume() {
super.onResume();
LayoutInflater inflater = LayoutInflater.from (this);
View v = inflater.inflate (R.layout.controls, null);
setTheme(getPreferenceTheme());
setContentView(v);
}
非常感谢任何帮助, M。
I'm having problems making my Activity respond to a theme change (i.e. Theme_Dark change to Theme_Light).
In the Activity this code below works fine, and the theme is changed when the Activity is created (method getPreferenceTheme() just gets the theme preference value that was set via a PreferenceActivity).
protected void onCreate(Bundle savedInstanceState) {
setTheme(getPreferenceTheme());
super.onCreate(savedInstanceState);
setContentView(R.layout.controls);
}
But how can I dynamically change the theme ? So after I change the theme in a PreferenceActivity and return to the main Activity how can I get it to change?
I know that I can re-start the Activity to do this (calling onCreate() again), but I didn't want to do this and have heard that it is possible to "re-inflate the view hierarchy" in onResume() - how do I do this ?
I tried the following (a stab in the dark) but with no joy.
protected void onResume() {
super.onResume();
LayoutInflater inflater = LayoutInflater.from (this);
View v = inflater.inflate (R.layout.controls, null);
setTheme(getPreferenceTheme());
setContentView(v);
}
Any help much appreciated,
M.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试“重新创建”活动方法。
http://developer.android.com/reference/android /app/Activity.html#recreate()
设置新主题后调用它。
Try the "recreate" Activity method.
http://developer.android.com/reference/android/app/Activity.html#recreate()
Call it after you have set the new theme.