How to set the font size of a text view equal to its size

advertisements

The code is a simple xml file containing a linear layout.Inside the linear layout , I have two text Views and a lnother linear layout, containing a button. I want to set the font size equal to height of the textview. We get the height using weight and weight sum method.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/orange"
    android:weightSum="100"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_weight="45"
        android:text="Coming Soon"
        android:gravity="center_vertical"
        android:background="@color/mainscreen" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_weight="10"
        android:text="TextView" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:layout_weight="45"
        android:background="@color/mainscreen">

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button" />

    </LinearLayout>

</LinearLayout>


You can achieve this programatically.

TextView defaultTextView = new TextView(context);
float sourceTextSize = defaultTextView.getTextSize();
TextView.setTextSize(sourceTextSize/getResources().getDisplayMetrics().density);

The defaultTextView.getTextSize() returns size in pixels and setTextSize(size) takes input as sp, So your text becomes bigger.

Here, instead of directly setting up the text size, first we are converting them according to density.