Se o usuário estiver fornecendo a entrada e a entrada precisar ser mostrada como TextView e se o usuário inserir as coisas que podem sair da tela, então, neste caso, a fonte TextView deve ser diminuída gradualmente. Portanto, neste artigo foi discutido como o desenvolvedor pode reduzir o tamanho de TextView gradualmente conforme o usuário fornece os dados. Pode-se dar uma olhada no seguinte GIF para entendê-lo melhor, o que vamos construir no final deste artigo. Observe que vamos implementar este projeto usando a linguagem Java .

Dimensionamento automático de TextView no Android

Etapas para dimensionamento automático de TextView

Neste artigo, o teclado de discagem é usado como exemplo. Este método pode ser usado na construção da calculadora e em muitos outros cenários onde o redimensionamento de TextView é necessário.

Etapa 1: crie um projeto do Android Studio com uma atividade vazia

Etapa 2: construir um layout apropriado trabalhando com o arquivo activity_main.xml

  • Como tomamos o teclado de discagem como exemplo para demonstrar o redimensionamento automático de TextView, invoque o seguinte código no arquivo activity_main.xml para tornar a IU como um teclado de discagem.
<?xml version="1.0" encoding="utf-8"?>
  
<!--the attributes further invoked for the 
     TextView are the part of Android Jetpac so we need to
     include xmlns:app="http://schemas.android.com/apk/res-auto" 
     as you can see below-->
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
                
    xmlns:app="http://schemas.android.com/apk/res-auto"
                
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText">
  
    <!--One needs to hardcode the height of the TextView-->
    <!--so that it can decrease its height automatically within-->
    <!--the given height and it doesn't disturbs the other widgets-->
    <!--one can set the maxLines of the TextViews upto which-->
    <!--the lines of the TextViews must be visible in this case its 2-->
    <TextView
        android:id="@+id/primaryTextView"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:hint="0"
        android:maxLines="2"
        app:autoSizeMaxTextSize="80sp"
        app:autoSizeMinTextSize="10sp"
        app:autoSizeStepGranularity="2sp"
        app:autoSizeTextType="uniform" />
  
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal"
        android:weightSum="3">
  
        <Button
            android:layout_width="68dp"
            android:layout_height="68dp"
            android:layout_margin="8dp"
            android:onClick="clickedOne"
            android:text="1"
            android:textSize="24sp" />
  
        <Button
            android:layout_width="68dp"
            android:layout_height="68dp"
            android:layout_margin="8dp"
            android:onClick="clickedTwo"
            android:text="2"
            android:textSize="24sp" />
  
        <Button
            android:layout_width="68dp"
            android:layout_height="68dp"
            android:layout_margin="8dp"
            android:onClick="clickedThree"
            android:text="3"
            android:textSize="24sp" />
  
    </LinearLayout>
  
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal"
        android:weightSum="3">
  
        <Button
            android:layout_width="68dp"
            android:layout_height="68dp"
            android:layout_margin="8dp"
            android:onClick="clickedFour"
            android:text="4"
            android:textSize="24sp" />
  
        <Button
            android:layout_width="68dp"
            android:layout_height="68dp"
            android:layout_margin="8dp"
            android:onClick="clickedFive"
            android:text="5"
            android:textSize="24sp" />
  
        <Button
            android:layout_width="68dp"
            android:layout_height="68dp"
            android:layout_margin="8dp"
            android:onClick="clickedSix"
            android:text="6"
            android:textSize="24sp" />
  
    </LinearLayout>
  
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal"
        android:weightSum="3">
  
        <Button
            android:layout_width="68dp"
            android:layout_height="68dp"
            android:layout_margin="8dp"
            android:onClick="clickedSeven"
            android:text="7"
            android:textSize="24sp" />
  
        <Button
            android:layout_width="68dp"
            android:layout_height="68dp"
            android:layout_margin="8dp"
            android:onClick="clickedEight"
            android:text="8"
            android:textSize="24sp" />
  
        <Button
            android:layout_width="68dp"
            android:layout_height="68dp"
            android:layout_margin="8dp"
            android:onClick="clickedNine"
            android:text="9"
            android:textSize="24sp" />
  
    </LinearLayout>
  
    <Button
        android:layout_width="68dp"
        android:layout_height="68dp"
        android:layout_gravity="center"
        android:layout_marginTop="8dp"
        android:onClick="clickedZero"
        android:text="0"
        android:textSize="24sp" />
  
</LinearLayout>
  • Pode-se ver os atributos de TextView no aplicativo de código acima : autoSizeMaxTextSize = ”80sp”, estes são os tamanhos iniciais de TextView.
  • app: autoSizeMinTextSize = ”10sp” usando este atributo, o TextView será redimensionado até o tamanho de 10sp e app: autoSizeStepGranularity = ”2sp” usando este atributo estamos uniformemente reduzindo o tamanho do TextView para 2sp quando sai da tela .
  • app: autoSizeTextType = ”uniforme” usando este atributo, estamos simplesmente redimensionando TextView uniformemente.
  • Uma coisa a lembrar é que não se deve definir a altura e a largura do TextView como wrap_content.
  • Para desativar o redimensionamento de TextView, pode definir este atributo como nenhum. Como você pode ver abaixo.

app: autoSizeTextType = ”none”

A seguinte IU de saída é produzida: 

Dimensionamento automático de TextView no Android

Etapa 3: agora lidando com cada botão separadamente, usando o atributo XML onClick 

  • Agora, no arquivo MainActivity.java , lidaremos com todas as funções onClick de cada Botão separadamente e definiremos o TextView para o número apropriado quando pressionado. Portanto, agora invoque o seguinte código:
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
  
public class MainActivity extends AppCompatActivity {
  
    TextView primaryTextView;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // register the button using appropriate ID of the TextView
        primaryTextView = findViewById(R.id.primaryTextView);
    }
  
    // handle the button 1 and append the 1 to the end of the TextView
    @SuppressLint("SetTextI18n")
    public void clickedOne(View view) {
        primaryTextView.setText(primaryTextView.getText() + "1");
    }
  
    // handle the button 2 and append the 2 to the end of the TextView
    @SuppressLint("SetTextI18n")
    public void clickedTwo(View view) {
        primaryTextView.setText(primaryTextView.getText() + "2");
    }
  
    // handle the button 3 and append the 3 to the end of the TextView
    @SuppressLint("SetTextI18n")
    public void clickedThree(View view) {
        primaryTextView.setText(primaryTextView.getText() + "3");
    }
  
    // handle the button 4 and append the 4 to the end of the TextView
    @SuppressLint("SetTextI18n")
    public void clickedFour(View view) {
        primaryTextView.setText(primaryTextView.getText() + "4");
    }
  
    // handle the button 5 and append the 5 to the end of the TextView
    @SuppressLint("SetTextI18n")
    public void clickedFive(View view) {
        primaryTextView.setText(primaryTextView.getText() + "5");
    }
  
    // handle the button 6 and append the 6 to the end of the TextView
    @SuppressLint("SetTextI18n")
    public void clickedSix(View view) {
        primaryTextView.setText(primaryTextView.getText() + "6");
    }
  
    // handle the button 7 and append the 7 to the end of the TextView
    @SuppressLint("SetTextI18n")
    public void clickedSeven(View view) {
        primaryTextView.setText(primaryTextView.getText() + "7");
    }
  
    // handle the button 8 and append the 8 to the end of the TextView
    @SuppressLint("SetTextI18n")
    public void clickedEight(View view) {
        primaryTextView.setText(primaryTextView.getText() + "8");
    }
  
    // handle the button 9 and append the 9 to the end of the TextView
    @SuppressLint("SetTextI18n")
    public void clickedNine(View view) {
        primaryTextView.setText(primaryTextView.getText() + "9");
    }
  
    // handle the button 0 and append the 0 to the end of the TextView
    @SuppressLint("SetTextI18n")
    public void clickedZero(View view) {
        primaryTextView.setText(primaryTextView.getText() + "0");
    }
}

Saída: Executar no emulador

Quer um ambiente mais competitivo e acelerado para aprender os fundamentos do Android?
Clique aqui para acessar um guia com curadoria exclusiva de nossos especialistas com o objetivo de torná-lo pronto para a indústria em nenhum momento!