[英]How to change font size programmatically in Android?
我需要在運行時更改應用程序的字體大小。 我參考了以下SO 帖子,其中他們談到通過 style.xml 應用字體大小並應用它。 我認為它僅適用於特定元素(如 TextView 或布局),但是否可以在應用程序級別應用字體大小,是否可以以編程方式設置?
獲取您的文本視圖TextView textView
setTextSize(size)
並應用setTextSize(size)
textView.setTextSize(20);
請注意,大小以像素為單位,而不是 style.xml 布局中的dp
是的,設置文字大小是:
textView.setTextSize(20)// text size
在這里添加了更多東西:)
1.如果你想設置為DP
textView.setTextSize(coverPixelToDP(20));
private int coverPixelToDP (int dps) {
final float scale = this.getResources().getDisplayMetrics().density;
return (int) (dps * scale);
}
2.如果你想自動調整字體大小以適應邊界使用,
setAutoSizeTextTypeUniformWithConfiguration(int autoSizeMinTextSize, int autoSizeMaxTextSize, int autoSizeStepGranularity, int unit)
JAVA版
TextView textView = new TextView(this);
textView.setText("Adjust font size for dynamic text");
//only works when width = 'match_parent', and give height
LinearLayout.LayoutParams p1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 500);
textView.setLayoutParams(p1);
textView.setAutoSizeTextTypeUniformWithConfiguration(8, 15, 1, TypedValue.COMPLEX_UNIT_DIP);
XML 版本(以編程方式)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent" // make sure it is match_parent
android:layout_height="500dp" //make sure you give height
app:autoSizeTextType="uniform"
app:autoSizeMinTextSize="12sp"
app:autoSizeMaxTextSize="100sp"
app:autoSizeStepGranularity="2sp" />
</LinearLayout>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.