I need to change the font size of my application at runtime. I referred the following SO post where they speak about applying font size via styles.xml and applying it. I think it's applicable only for a particular element (like TextView or layout) but is it possible to apply the font size at application level and is it possible to set it programmatically?
Take your text view TextView textView
and apply setTextSize(size)
textView.setTextSize(20);
Note that size is in pixels, not dp
as in styles.xml layout
Yes, setting text size is :
textView.setTextSize(20)// text size
added few more things here :)
1.If you want to set as DP
textView.setTextSize(coverPixelToDP(20));
private int coverPixelToDP (int dps) {
final float scale = this.getResources().getDisplayMetrics().density;
return (int) (dps * scale);
}
2.If you want to adjust font size automatically to fit boundaries use,
setAutoSizeTextTypeUniformWithConfiguration(int autoSizeMinTextSize, int autoSizeMaxTextSize, int autoSizeStepGranularity, int unit)
JAVA Version
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 Version (Programatically)
<?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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.