问题/需求来源
在项目开发过程中,发现 5.0以上Button的字体自动转换为大写,中文情况下,并没有多大影响,开发英文界面的时候会与UI/UE给出的效果有所不同,有时候会需要原文显示,所以需要修改去掉大写属性。
问题分析
通过源码发现在5.0中关于Button是使用Theme的 android:textAppearanceButton"
属性,内容如下
<style name="TextAppearance.Material.Button">
<item name="textSize">@dimen/text_size_button_material</item>
<item name="fontFamily">@string/font_family_button_material</item>
<item name="textAllCaps">true</item>
<item name="textColor">?attr/textColorPrimary</item>
</style>
代码中可以看到 textAllCaps=true
这个属性将按钮的文本变为大写。
解决方案/方法
方法1
直接手动修改,即在用到 Button 的XML布局/代码中修改
<Button
android:layout_width="wrap_content"
android:textAllCaps="false"//修改属性不转换大写
android:layout_height="wrap_content" />
或者
button.setAllCaps(false);
如果修改的地方很多,可以自定义Button的属性,通过父类继承的方式实现。
方法2
方法1需要逐一修改,操作起来很繁琐,有没有更加简单的方式?
当然是有的,既然原生的系统可以通过修改样式的方式达到全局修改,那么我们只要覆盖掉 textAllCaps=true
这个属性就也可以达到相同的目的。
首先,创建一个Button的Style(文中的NewButtonStyle
),继承5.0的系统样式,当然了,也可以继承其他样式
<style name="NewButtonStyle" parent="android:TextAppearance.Material.Button">
<item name="android:textAllCaps">false</item>
</style>
然后创建一个主题样式,为你的Activity提供定制化样式(文中的NewAppTheme
),同时在样式中替换掉原先的 android:textAppearanceButton
属性
<style name="NewAppTheme" parent="android:Theme.Material">
<!--去掉按钮默认大小字体的-->
<item name="android:textAppearanceButton">@style/NewButtonStyle</item>
......
</style>
最后,让你需要使用到这个属性的Actvity中配置,可以在 AndroidManifest.xml
中使用属性
<activity
android:name=".WelcomeActivity"
android:theme="@style/NewAppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
或者在你的Activity的onCreate
中,在super.onCreate(savedInstanceState);
之前添加setTheme(R.style.NewAppTheme);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
//一定要在super.onCreate(savedInstanceState)之前才有效
setTheme(R.style.NewAppTheme);
super.onCreate(savedInstanceState);
......
}
总结
上面方法也可以用在自定义Dialog的布局样式中,使用方法一样,在这里不再冗述。希望能够有所帮助