Android 如何将textview的字体大小设置为其高度

Android 如何将textview的字体大小设置为其高度,android,android-layout,Android,Android Layout,代码是一个简单的xml文件,包含一个线性布局。在线性布局中,我有两个文本视图和一个其他线性布局,其中包含一个按钮。 我想将字体大小设置为文本视图的高度。我们使用重量和重量总和法得到高度 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_pare

代码是一个简单的xml文件,包含一个线性布局。在线性布局中,我有两个文本视图和一个其他线性布局,其中包含一个按钮。 我想将字体大小设置为文本视图的高度。我们使用重量和重量总和法得到高度

<?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>

您可以通过编程实现这一点

TextView defaultTextView = new TextView(context);
float sourceTextSize = defaultTextView.getTextSize();
TextView.setTextSize(sourceTextSize/getResources().getDisplayMetrics().density);
getTextSize()返回以像素为单位的大小,setTextSize(size)将输入作为sp,因此文本会变大

在这里,我们不是直接设置文本大小,而是首先根据密度进行转换。

我们不能设置文本大小,例如换行内容、填充父项或匹配父项
    We can not set text size like wrap_content,fill_parent or match_parent 
as like textview height so, if you need to set text size equals to 
Textview height than you need to go for fix textview height and text 
size like.... 
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:text="@string/hello_world" 
            android:textSize="50dp"/>
与textview高度一样,如果需要将文本大小设置为 文本视图高度比您需要的要高,以固定文本视图高度和文本 大小像。。。。
为textview绘制一个可绘制的形状


并将其置于textview背景属性中

<solid android:color="@color/your_background_coler"/>