分三种情况
- 一个TextView中部分文字改变大小和样式;
- 部分页面统一改变文字大小;
- 全局改变文字大小;
情况一:
Spannable span = new SpannableString("2014-09-07");
span.setSpan(new RelativeSizeSpan(1.5f), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
span.setSpan(new ForegroundColorSpan(Color.RED), 0, 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
span.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mTvDate.setText(span);
情况二:
实现自定义TextView,重写setTextSize方法,同时自定义textSize属性
public class ChangeSizeTextView extends androidx.appcompat.widget.AppCompatTextView {
private float textSize;
public ChangeSizeTextView(Context context) {
super(context);
}
public ChangeSizeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray array=context.obtainStyledAttributes(attrs, R.styleable.ChangeSizeTextView);
textSize = array.getDimension(
R.styleable.ChangeSizeTextView_changableTextSize, 0f);
if (textSize != 0f) {
setTextSize(textSize);
}
}
public ChangeSizeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setTextSize(float size) {
this.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
}
@Override
public void setTextSize(int unit, float size) {
if (ApplicationSharedPreferences.getFontSetting() == 1) {
size*= MainApplication.FONT_SIZE;
}
super.setTextSize(unit, size);
}
}
<declare-styleable name="ChangeSizeTextView">
<attr name="changableTextSize" format="dimension"/>
</declare-styleable>
<包名.ChangeSizeTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="个人中心"
android:textColor="@color/tab_home_text_color_selector"
app:changableTextSize="12sp" />
情况三:
private void resizeFontSize(Context context) {
Resources res = context.getResources();
Configuration config = res.getConfiguration();
if (ApplicationSharedPreferences.getFontSetting() == 0) {
config.fontScale = 1.0f; // 默认字体尺寸值为1.0f
} else {
config.fontScale = MainApplication.FONT_SIZE;
}
res.updateConfiguration(config, res.getDisplayMetrics());
}
通过SharedPreferences保存变量的方式控制版本
private final static String FONT_SIZE_TYPE = "font_size_type";
/** 获取菜单文字版本, 分为普通版0和大字版1 */
public static int getFontSetting() {
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(MainApplication.context);
return preferences.getInt(FONT_SIZE_TYPE, 0);
}
/** 保存菜单文字版本, 分为普通版0和大字版1 */
public static void setFontSetting(int fontSizeType) {
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(MainApplication.context);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(FONT_SIZE_TYPE, fontSizeType);
editor.commit();
}
重启App后才生效
public void restartApplication(Context context) {
final Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
}