본문 바로가기
안드로이드 자바

[Java][Android] AutoFitTextView 사용하기

by teamnova 2022. 11. 27.
728x90

안녕하세요. 

오늘은 AutoFitTextView 를 사용해서 텍스트 길이에 따라 View 와 Font 의 Size 조절되는 TextView를 만들어보겠습니다.

 

1. 라이브러리 등록

repositories {
        mavenCentral()
}

dependencies {
		implementation 'me.grantland:autofittextview:0.2.1'
}

 

2. XML 생성

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/Nomal_txt"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_marginTop="4dp"
        android:maxLines="2"
        android:text="Nomal : "
        android:textSize="40sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <me.grantland.widget.AutofitTextView
        android:id="@+id/Auto_txt"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:maxLines="2"
        android:text="Auto : "
        app:minTextSize="16sp"
        android:textSize="40sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/Nomal_txt" />

    <EditText
        android:id="@+id/edit_txt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="아무거나"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

3. MainActivity 작성

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.editTxt.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) {
                binding.AutoTxt.setText("Auto : " + binding.editTxt.getText());
                binding.NomalTxt.setText("Nomal : " + binding.editTxt.getText());
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }
AutoFitText 시연 영상