Android动态设置主题样式
16lz
2021-01-25
有时候需要在App中提供不同的主题给用户选择,这就需要在app中动态设置主题样式,效果如图所示:
在style.xml中设置主题属性:
-- Base application theme. -->
因为TextView的文字和背景颜色要随主题变化,所以需要在每个主题中指定对应的颜色(colorText和colorTextBackground),并且要在attrs.xml中申明颜色变量:
<?xml version="1.0" encoding="utf-8"?><resources> <attr name="colorText" format="reference|color"/> <attr name="colorTextBackground" format="reference|color"/>resources>
在TextView中指定对应颜色:
"@+id/message" android:text="Test text" android:gravity="center" android:textSize="20sp" android:background="?attr/colorTextBackground" android:textColor="?attr/colorText" android:layout_weight="1" android:layout_width="match_parent" android:layout_height="0dp"/>
在activity中进行设置:
public class MainActivity extends AppCompatActivity { private TextView mTextMessage; private static int sMessage; private static int sTheme; private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_blue: sMessage = R.string.title_blue; //将选中的主题资源id保存到静态变量中 sTheme = R.style.AppThemeLightBlue; //重构Activity才能应用新的主题 recreate(); return true; case R.id.navigation_deep_blue: sMessage = R.string.title_deep_blue; sTheme = R.style.AppThemeDeepBlue; recreate(); return true; case R.id.navigation_green: sMessage = R.string.title_green; sTheme = R.style.AppThemeGreen; recreate(); return true; case R.id.navigation_pink: sMessage = R.string.title_pink; sTheme = R.style.AppThemePink; recreate(); return true; } return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (sTheme!=0) { //设置主题 setTheme(sTheme); } setContentView(R.layout.activity_main); mTextMessage = (TextView) findViewById(R.id.message); if (sMessage!=0) mTextMessage.setText(sMessage); BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); }}
更多相关文章
- Android---配置adb环境变量
- android ndk 给结构体赋值的方法
- Android(安卓)- RGB颜色查询对照表
- Android(安卓)下的 makefile 组织结构
- Android多视图(View)切换
- ubuntu gradle编译总结
- 酷炫的android dialog弹出框
- Android中EditText的错误消息显示
- 一步一步学Android(一)