Android自动调整TextView的大小

本文介绍了如何在Android应用中实现TextView的自动调整大小功能,包括在Oreo及更高版本上的使用、向后兼容的解决方案,以及编程方式的设置。通过预设、粒度和最小/最大文本大小来控制文本自动调整。
摘要由CSDN通过智能技术生成

In this tutorial, we’ll look at how we can implement TextView such that it auto resizes itself based on the available space and properties specified in our Android Application.

在本教程中,我们将研究如何实现TextView,使其能够根据Android应用程序中指定的可用空间和属性自动调整自身大小。

自动调整TextView的大小 (Auto-Sizing TextView)

Auto-sizing TextView was introduced with Android Oreo. Provided you set the required properties, the text size would automatically change inside its view. Auto-sizing TextView supports backward compatibility all the way till API 4.

Android Oreo引入了自动调整TextView大小的功能。 如果您设置了必需的属性,则文本大小将在其视图内自动更改。 自动调整TextView的大小一直支持向后兼容,直到API 4。

To use Auto-sizing TextView you must use SDK 26 dependency or above:

要使用自动调整TextView大小,您必须使用SDK 26依赖关系或更高版本:

implementation 'com.android.support:appcompat-v7:26.1.0'

Following are the core properties you must add on the TextView to enable Auto-sizing TextView:

以下是您必须在TextView上添加的核心属性才能启用自动调整TextView的大小:

  • android:autoSizeTextType – This is set to the value uniform or none. Uniform sizes the text uniformly vertically and horizontally

    android:autoSizeTextType –设置为统一值或值。 统一在垂直和水平方向上均匀调整文本大小
  • android:autoSizeMaxTextSize – Maximum text size for the TextView

    android:autoSizeMaxTextSize – TextView的最大文本大小
  • android:autoSizeMinTextSize – Minimum text size for the TextView

    android:autoSizeMinTextSize – TextView的最小文本大小

An Auto-sizing TextView can be defined in the xml as:

可以在xml中将自动调整大小的TextView定义为:

<TextView
        android:id="@+id/autoTextView"
        android:layout_width="match_parent"
        android:layout_height="125dp"
        android:text="Resizable TextView here."
        android:autoSizeMaxTextSize="100sp"
        android:autoSizeMinTextSize="12sp"
        android:autoSizeTextType="uniform" />
NOT use WRAP_CONTENT. 不要使用WRAP_CONTENT

How is the text auto-sized?

文字如何自动调整大小?

There are three ways to do it:

有三种方法可以做到:

  • Default – Size changes happen by 1 px. That means granularity is 1 px

    默认值 -尺寸更改发生1像素。 这表示粒度为1像素
  • Granularity – This is a dimension by which the text size increases or decreases in steps between the minimum and maximum text size. Example : android:autoSizeStepGranularity="2sp" increments/decrements the text size by 2 sp.

    粒度 –这是一个尺寸,文本大小可在最小和最大文本大小之间逐步增大或减小。 示例: android:autoSizeStepGranularity="2sp"将文本大小增加/减少2 sp。
  • Presets – This is used to auto-size the text from an array of predefined text size values.

    预设 –用于从一组预定义的文本大小值中自动调整文本大小。

使用预设 (Using Presets)

We can define the predefined in an arrays.xml in the values folder.

我们可以在values文件夹的arrays.xml中定义预定义。

<resources>
  <array name="autosize">
    <item>10sp</item>
    <item>30sp</item>
    <item>20sp</item>
    <item>40sp</item>
    <item>100sp</item>
  </array>
</resources>

Set this in the TextView as:

在TextView中将此设置为:

<TextView
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:autoSizeTextType="uniform"
    app:autoSizePresetSizes="@array/autosize" />

自动调整Or-Preeo设备的尺寸 (Auto-size for Pre-Oreo Devices)

The above properties work fine only on Android Oreo and above. To make it compatible with the older version we need to do two things:

以上属性仅在Android Oreo及更高版本上可以正常使用。 为了使其与旧版本兼容,我们需要做两件事:

  • Use AppCompatTextView widget in place of TextView

    使用AppCompatTextView小部件代替TextView
  • Use app: nomenclature

    使用app:术语

Define the Auto-size TextView in the XML as:

在XML中定义自动调整大小的TextView为:

<android.support.v7.widget.AppCompatTextView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:text="TextView"
        app:autoSizeMaxTextSize="100sp"
        app:autoSizeMinTextSize="8sp"
        app:autoSizeStepGranularity="2sp"
        app:autoSizeTextType="uniform"
        />

以编程方式自动调整TextView的大小 (Auto-size TextView programmatically)

To set properties on the Auto-size TextView programmatically we use the TextViewCompat class.

要以编程方式在自动调整大小的TextView上设置属性,我们使用TextViewCompat类。

You need to pass the TextView instance and the respective sizes for the properties.

您需要传递TextView实例以及属性的相应大小。

Set the autoSize text types as: TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE or TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM.

将autoSize文本类型设置为: TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONETextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM

Setting Presets programmatically:

以编程方式设置预设:

To set the presets programmatically you need to define the arrays.xml differently.

要以编程方式设置预设,您需要不同地定义arrays.xml。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="autosize">
        <item>20</item>
        <item>40</item>
        <item>50</item>
        <item>60</item>
        <item>70</item>
    </array>
</resources>

To set it on the TextView do the following:

要在TextView上进行设置,请执行以下操作:

TextViewCompat.setAutoSizeTextTypeUniformWithPresetSizes(textView, getResources().getIntArray(R.array.autosize), TypedValue.COMPLEX_UNIT_SP);

Let’s build an android application that demonstrates the various use cases of Auto-sizing TextView.

让我们构建一个Android应用程序,演示自动调整TextView大小的各种用例。

项目结构 (Project Structure)

(Code)

The code for the activity_main.xml layout is given below:

下面给出了activity_main.xml布局的代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="125dp"
        android:background="@android:color/black"
        android:text="Not resizable TextView. The text size is fixed here."
        android:textColor="@android:color/white"
        app:layout_constraintEnd_toStartOf="@+id/autoTextView"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextPreset" />

    <android.support.v7.widget.AppCompatTextView
        android:id="@+id/autoTextView"
        android:layout_width="0dp"
        android:layout_height="125dp"
        android:background="@android:color/black"
        android:text="Resizable TextView here. This can vary the text size based on it."
        android:textColor="@android:color/white"
        app:autoSizeMaxTextSize="100sp"
        app:autoSizeMinTextSize="12sp"
        app:autoSizeStepGranularity="2sp"
        app:autoSizeTextType="uniform"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/textView"
        app:layout_constraintTop_toBottomOf="@+id/editTextPreset" />

    <android.support.v7.widget.AppCompatTextView
        android:id="@+id/autoTextViewDynamic"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:autoSizeMaxTextSize="100sp"
        app:autoSizeMinTextSize="8sp"
        app:autoSizeStepGranularity="2sp"
        app:autoSizeTextType="uniform"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="Enter here"
        android:maxLines="1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/autoTextViewDynamic" />


    <EditText
        android:id="@+id/editTextPreset"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="Enter here for preset size changes"
        android:maxLines="1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText" />


    <android.support.v7.widget.AppCompatTextView
        android:id="@+id/autoTextViewEllipsize"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="16dp"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="Auto sizing TextView with ellipsize at the end. AppCompat TextVie2"
        app:autoSizeMaxTextSize="100sp"
        app:autoSizeMinTextSize="16sp"
        app:autoSizeStepGranularity="2sp"
        app:autoSizeTextType="uniform"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</android.support.constraint.ConstraintLayout>

We’ve added an ellipisize property on one of the Auto-sizing TextView. This way if the content is filled at min text size the remaining Text is truncated

我们在自动调整大小的TextView之一上添加了ellipisize属性。 这样,如果内容以最小文本大小填充,则剩余文本将被截断

The code for the MainActivity.java class is given below:

MainActivity.java类的代码如下:

package com.journaldev.androidautosizingtextview;

import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView txtAutoSizeTextViewDynamic = findViewById(R.id.autoTextViewDynamic);
        final TextView textView = findViewById(R.id.textView);
        EditText editText = findViewById(R.id.editText);
        EditText editTextWithPresetChanges = findViewById(R.id.editTextPreset);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {



            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                txtAutoSizeTextViewDynamic.setText(charSequence.toString());

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        editTextWithPresetChanges.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                TextViewCompat.setAutoSizeTextTypeUniformWithPresetSizes(textView, getResources().getIntArray(R.array.autosize), TypedValue.COMPLEX_UNIT_SP);
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                textView.setText(charSequence);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }
}

We’ve added TextWatchers on two of the EditTexts which will update the Auto-sizing TextViews whenever the edit text is changed.

我们已经在两个EditText上添加了TextWatchers,它们将在更改编辑文本时更新自动调整大小的TextView。

We’ve changed the normal text view to an auto-sizing one when text is entered in the second EditText.

在第二个EditText中输入文本时,我们已将普通文本视图更改为自动调整大小的视图。

The output of the above application in action is given below:

上面应用程序的输出如下:

This brings an end to this tutorial. You can download the project from the link below:

本教程到此结束。 您可以从下面的链接下载项目:

翻译自: https://www.journaldev.com/22399/android-auto-sizing-textview

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android Studio中设置TextView的字体大小可以通过在XML布局文件中设置android:textSize属性来实现。例如,可以使用以下代码设置字体大小为18sp: ```xml <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:textSize="18sp" /> ``` 在这个例子中,字体大小被设置为18sp。sp是一种适用于文本的单位,它会根据用户的系统字体大小设置进行自适应调整。这意味着,如果用户在系统设置中将字体大小调大,那么TextView中的文本也会相应地变大。这是由Android系统的自动调整文本大小特性实现的。\[1\] 在Java代码中,可以使用TextView的setTextSize方法来动态设置字体大小。例如,可以使用以下代码将字体大小设置为30sp: ```java TextView textView = findViewById(R.id.textView); textView.setTextSize(30); ``` 在这个例子中,setTextSize方法的第一个参数是单位,可以使用TypedValue类中的常量来指定单位,例如TypedValue.COMPLEX_UNIT_SP表示sp单位。第二个参数是具体的字体大小。\[2\]在这种情况下,30是字体大小,而单位默认为sp。 请注意,如果在XML布局文件中已经设置了android:textSize属性,那么在Java代码中调用setTextSize方法将会覆盖XML中的设置。\[3\] #### 引用[.reference_title] - *1* [【AndroidTextView字体大小自适应的方式](https://blog.csdn.net/weixin_44002043/article/details/128833267)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [【Android Studio程序开发】文本显示--设置文本的大小](https://blog.csdn.net/qq_64976935/article/details/127128447)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值