在不重新创建的情况下为特定视图应用新主题 Activity
Apply new theme for a particular view without recreating Activity
我的应用程序一次显示 6 个片段,因此重新创建 activity 不是一个好的选择,因为它会使屏幕闪烁并在重新分级保存和恢复活动和片段的状态时面临一些意外问题。
我也不想遍历视图层次结构并更改每个视图,因为有很多属性需要更改。
我只需要为 NavigationView
应用一个新的主题(样式),它隐藏在屏幕旁边,稍后会显示。特别是,我想更改这些属性:
itemBackground
、itemIconTint
、itemTextColor
感谢Mike M
我用他的方法解决了这个问题:
public void updateNavigationViewLayout(){
drawerLayout.removeView(navigationView);
LayoutInflater inflater = LayoutInflater.from(new ContextThemeWrapper(this, R.style.newtheme));
drawerLayout = (DrawerLayout) inflater.inflate(R.layout.navigation_drawer, drawerLayout);
navigationView = drawerLayout.findViewById(R.id.nav_view);
}
记得将navigationView引用到新的。否则,第二次调用此方法时,新的 NagivationView 不会被删除,您将添加一个额外的 NavigationView 导致此错误:
Child drawer has absolute gravity LEFT but this DrawerLayout already has a drawer view along that edge
我的应用程序一次显示 6 个片段,因此重新创建 activity 不是一个好的选择,因为它会使屏幕闪烁并在重新分级保存和恢复活动和片段的状态时面临一些意外问题。
我也不想遍历视图层次结构并更改每个视图,因为有很多属性需要更改。
我只需要为 NavigationView
应用一个新的主题(样式),它隐藏在屏幕旁边,稍后会显示。特别是,我想更改这些属性:
itemBackground
、itemIconTint
、itemTextColor
感谢Mike M
我用他的方法解决了这个问题:
public void updateNavigationViewLayout(){
drawerLayout.removeView(navigationView);
LayoutInflater inflater = LayoutInflater.from(new ContextThemeWrapper(this, R.style.newtheme));
drawerLayout = (DrawerLayout) inflater.inflate(R.layout.navigation_drawer, drawerLayout);
navigationView = drawerLayout.findViewById(R.id.nav_view);
}
记得将navigationView引用到新的。否则,第二次调用此方法时,新的 NagivationView 不会被删除,您将添加一个额外的 NavigationView 导致此错误:
Child drawer has absolute gravity LEFT but this DrawerLayout already has a drawer view along that edge