A TextView that automatically fit its font and line count based on its available size and content

Overview

Release

AutoFitTextView

A TextView that automatically fit its font and line count based on its available size and content

This code is heavily based on this StackOverflow thread.

The sample shows how the library can handle various parameters being changed on the TextView: width, height, number of lines allowed, and the content (text) itself. You can play with the various properties to see how the library handle them.

Note that even though the sample is of API 17, it should work fine on most cases for API 14 and above.

A nice example of how to use an EditText that has this functionality can be found here (didn't test it, but it looks promising).

Preview

preview animation

Import using Gradle

allprojects {
	repositories {
		...
		maven { url "https://jitpack.io" }
	}
}

	dependencies {
        implementation 'com.github.AndroidDeveloperLB:AutoFitTextView:XXX'
}

You can find recent version here (replace XXX):

https://jitpack.io/#AndroidDeveloperLB/AutoFitTextView

Comments
  • Size gets crazy inside a cardView in recyclerView

    Size gets crazy inside a cardView in recyclerView

    Hi!,

    I've a recyclerView with a lot of cardView. Each cardView has an autoResizeTextView and when I scroll fastly (down & up) the autoResizeTextView gets crazy... too much little in the most of time.

    How Can I resolve this?

    thanks in advance!

    opened by oskarko 18
  • when i add onclick attribute, application crashes

    when i add onclick attribute, application crashes

    hey guy, what's up? i have problem, when i add android:onclick="..." attr in AutoResizeTextView and after the run it, when i click on the AutoResizeTextView ,application crashes and force close! but when I change the AutoResizeTextView to TextView, the problem is fixed i think this is a bug and should be fix it to make better library

    opened by saeedm1 16
  • When AutoResizeTextView is used in a custom view for a TabLayout.Tab, the text progressively gets smaller as the tab is selected and reselected

    When AutoResizeTextView is used in a custom view for a TabLayout.Tab, the text progressively gets smaller as the tab is selected and reselected

    Layout of custom view for Tab:

    <AutoResizeTextView xmlns:android="http://schemas.android.com/apk/res/android"
                                                     xmlns:tools="http://schemas.android.com/tools"
                                                     android:id="@+id/tab_title"
                                                     android:layout_width="wrap_content"
                                                     android:layout_height="wrap_content"
                                                     android:layout_gravity="center"
                                                     android:maxLines="1"
                                                     android:textSize="18sp"
                                                     android:textStyle="bold"/>
    

    Code for setting up TabLayout in Activity:

    _tabLayout.setupWithViewPager(_viewPager);
    _tabLayout.setTabGravity(TabLayout.GRAVITY_CENTER);
    _tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(_viewPager)
            {
                @Override
                public void onTabSelected(TabLayout.Tab tab)
                {
                    _viewPager.setCurrentItem(tab.getPosition(), true);
    
                    ViewHolder viewHolder = (ViewHolder) tab.getTag();
    
                    viewHolder.TabTitleView.setTextColor(getResources().getColor(R.color.primaryColor));
    
                    viewHolder.TabTitleView.setText(_pageAdapter.getPage(tab.getPosition()).getSelectedTitle());
                }
    
                @Override
                public void onTabUnselected(TabLayout.Tab tab)
                {
                    ViewHolder viewHolder = (ViewHolder) tab.getTag();
    
                    viewHolder.TabTitleView.setTextColor(getResources().getColor(R.color.tab_title_color));
                    viewHolder.TabTitleView.setText(_pageAdapter.getPage(tab.getPosition()).getTitle());
                }
            });
    
            for(int i = 0; i < _pageAdapter.getCount(); i++)
            {
                TabLayout.Tab tab = _tabLayout.getTabAt(i);
                tab.setCustomView(R.layout.tab_title);
    
                ViewHolder viewHolder = new ViewHolder(tab.getCustomView(), _tabLayout.getContext());
                viewHolder.TabTitleView.setText(_pageAdapter.getPage(i).getTitle());
                tab.setTag(viewHolder);
    
                if(i == 0)
                    viewHolder.TabTitleView.setTextColor(getResources().getColor(R.color.primaryColor));
            }
    
    opened by afahrenholtzmcgladrey 16
  • Truncated Word

    Truncated Word

    I have a layout that has two columns, they are defined as LinearLayout, see code below. I think AutoFixTextView does not take into account the size of the LinearLayout it is contained in, but one level up. This results in the word being truncated, see the attached screen-shot (it should end with PNG).

    <?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:orientation="horizontal"
        android:layout_gravity="center_vertical"
        android:background="@drawable/my_background_border"
        >
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_gravity="center_vertical"
            android:background="@drawable/my_background_border"
            >
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:orientation="vertical"
                android:layout_weight="1"
                android:gravity="center"
                android:background="@drawable/my_background_border"
                >
                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/previous_card"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical|left"
                    android:src="@drawable/navigate_previous" />
                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/next_card"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical|left"
                    android:src="@drawable/navigate_next" />
    
            </LinearLayout>
        </LinearLayout>
    
        <LinearLayout
            android:id="@+id/card_text_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_gravity="center_vertical"
            android:background="@drawable/my_background_border"
            >
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:orientation="vertical"
                android:layout_weight="1"
                android:gravity="center"
                android:background="@drawable/my_background_border"
                >
                <com.thedatawise.www.toddlerflip.AutoResizeTextView
                    android:id="@+id/card_back_text"
                    android:textColor="#000"
                    android:textAllCaps="true"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:gravity="center_vertical"
                    android:textSize="100sp"
                    android:text="BACK PAGE" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
    

    capture _2016-03-05-22-18-38

    opened by mpekalski 12
  • Bug: Don't chain constructors with this().

    Bug: Don't chain constructors with this().

    The problems caused by this() are most evident when changing the base class from TextView to it's close relative EditText. The EditText behaves rather oddly because it's never gets set up with some important default internal styles (see Android source for EditText(Context, AttributeSet)).

    Your current code has the two simpler constructors calling the 3-argument constructor via 'this(context, attrs, 0)'. The derived constructors should be calling super(), not this() and also calling a common init() method which contains the autofit init code.

    opened by reubenscratton 8
  • Doesn't auto resize in the first time

    Doesn't auto resize in the first time

    • I am trying to use AutoResizeTextView on a simple activity, but it fails on the first go. If the button is touched to auto resize there is no problem. But, the thing is, i need it to be resized when the activity is first created.
    • Here is the list of things i have tried: Created AutoRiseTextView in xml as a CustomView. Called "show_the_text" method twice on the start. Called the method twice with different texts. Moved container decleration to inside of onCreate. Used RelativeLayout insted of FrameLayout. Created a temporary TextView inside of FrameLayout with text in it.
    • I run the application on API23 emulator and API21 phone but result is the same.
    • I have to say that i am a begginer in programming. Any ideas are welcome.

    oncreateview

    JAVA FILE

         public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            //auto resizing fails on the first run
            show_auto_resized_text();
    
            //but when we use user touch it works
            TextView button=(TextView) findViewById(R.id.text_button);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    show_auto_resized_text();
                }
            });
        }
        public void show_auto_resized_text(){
            FrameLayout text_container=(FrameLayout) findViewById(R.id.container);
            text_container.removeAllViews();
            int width= text_container.getWidth()-40;
            int height= text_container.getHeight()-40;
            AutoResizeTextView textView=new AutoResizeTextView(MainActivity.this);
            textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
            textView.setMaxLines(10);
            textView.setTextColor(Color.WHITE);
                    textView.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, height, getResources().getDisplayMetrics()));
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setLayoutParams(new ViewGroup.LayoutParams(width, height));
            final String DOUBLE_BYTE_SPACE = "\u3000";
            String fixString = "";
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR1
            && android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                fixString = DOUBLE_BYTE_SPACE;
            }
            textView.setText(fixString + "THIS IS MY TEXT TO BE AUTO RESIZED" + fixString);
            text_container.addView(textView);
        }
    }
    

    XML FILE

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.kr.hakan.myapplication.MainActivity">
    
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentTop="true"
            android:layout_above="@+id/text_button"
            android:background="#ff5b14"
            android:layout_margin="20dp"
            android:id="@+id/container"></FrameLayout>
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Auto Resize The Text"
            android:id="@+id/text_button"
            android:layout_alignParentBottom="true"
            android:background="#000000"
            android:textSize="30sp"
            android:textColor="#ffffff"
            android:gravity="center" />
    </RelativeLayout>
    
    opened by hakan6000 8
  • check for textAllCaps

    check for textAllCaps

    When property of layout textAllCaps was set to true, the string got fit to view before the caps were applied. This fix checks if the property is set, makes the string upper case if true, and then performs the fit.

    opened by mpekalski 8
  • Home widget

    Home widget

    Hi, I trie to add it in the home widget but I always get Problem loading widget and the widget does not get displayed. Any ideas how to solve this problem?

    opened by salvolf 7
  • Set text size method clarification

    Set text size method clarification

    Hi! Please can you clarify the usage of setTextSize method in the sample project here. I just can't wrap my head around it. What I need is to auto size a text font in accordance with the given width and height bounds. But according to the sample the text size should be set beforehand.

    So how can I determine the initial text size to make the autosizing work? Thanks in advance.

    opened by stanmots 6
  • Resizing getting always smaller

    Resizing getting always smaller

    Hi, i'm using your library that i found very usefull. But i've some problem with it. I'm making a back and forth between two activites and every time i came back on the first one the text is getting smaller and smaller and smaller again. Is it possible to stop this?? and with big text size like 150sp is it possible to erase the font padding top and bottom??

    PS: I think import android.annotation.TargetApi is deprecated

    opened by thomaslc66 6
  • Add Edit Text for auto fitting

    Add Edit Text for auto fitting

    Repo ->

    • https://github.com/ViksaaSkool/AutoFitEditText
    • my fork
      • https://github.com/CrandellWS/AutoFitEditText
      • set lib up to be used as a git submodule
        • https://github.com/CrandellWS/AutoFitEditTextLib

    For a quick how to:

    # add submodule to track master branch
    git submodule add -b master [URL to Git repo];
    
    # update your submodule
    git submodule update --remote 
    

    so it goes like this:

    git submodule add  https://github.com/CrandellWS/AutoFitEditTextLib 
    git submodule update --remote 
    

    See What you can do...But basically I need to use both libs because yours is TextView and the other is EditText.

    opened by CrandellWS 5
  • Allow the text to grow to fit the space imposed by its parent

    Allow the text to grow to fit the space imposed by its parent

    If the view's dimensions grow, the text size did not grow because AutoFitTextView was using its existing dimensions as a maximum size. Now it retains the maximum dimensions set by its parent during the measure pass.

    A sample activity is included to show the AutoFitTextView adjusting to the size constraints imposed by its parent. Without the above change, the text size would shrink but never grow.

    While testing, I noticed that setting the text size to X would result in an actual text size of X-1 if there were no size constraints, so I fixed binarySearch.

    opened by Klox 2
  • This library failed if only emojies text

    This library failed if only emojies text

    I am using this library in my project. But library is not working if string has only emojis.

    "message":"😉😊"

    See 1 user send only emojis. and app crashed in production version. Android 10

    opened by hardikJoshi123 1
  • Hebrew words are cut in the bottom of last line

    Hebrew words are cut in the bottom of last line

    In my app I have sentence with full screen width on a welcome screen. When text is in a Hebrew language the words are cut in the bottom of last line.

    Adding bottom padding or setting clipToPadding/clipChildren don't help.

    Can't use the Google autosizing TextView because it still has a "breaking the words issue".

    opened by thecodeside 1
  • Dosen't work with Chinese multiline sentence

    Dosen't work with Chinese multiline sentence

    I have found a bug, when it is all Chinese sentence and more then one line, the textsize would be divided to min size. It is because: https://github.com/AndroidDeveloperLB/AutoFitTextView/blob/master/AutoFitTextViewLibrary/src/com/lb/auto_fit_textview/AutoResizeTextView.java#L89

    in Chinese sentence, words was not linked by or - so the method isValidWordWrap return false everytime in Chinese sentence, and then the sizebecome smaller and smaller(;′⌒`)

    opened by KB5201314 1
Owner
Almost always develops for Android, using Kotlin&Java.
null
A TextView that changes its content automatically every few seconds

FadingTextView A TextView that changes its content automatically every few seconds Demo app A demo app is available on Google Play: Usage Add this to

Tomer Rosenfeld 1.7k Dec 9, 2022
A TextView library that allows the user to increase/decrease font size with a two finger gesture by the user.

PinchZoomTextView Library This library allows you to have a TextView that will grow/shrink the font size using gestures from the user. Usage To have a

null 311 Nov 23, 2022
An extension of Android's TextView, EditText and Button that let's you use the font of your choice

AnyTextView (deprecated) Note: AnyTextView is no longer being maintained. I recommend replacing AnyTextView with the Calligraphy library instead. Frus

Hans Petter Eide 165 Nov 11, 2022
AutoLinkTextView is TextView that supports Hashtags (#), Mentions (@) , URLs (http://), Phone and Email automatically detecting and ability to handle clicks.

AutoLinkTextView Deprecated Please use the new version of AutoLinkTextView AutoLinkTextView is TextView that supports Hashtags (#), Mentions (@) , URL

Arman 1.1k Nov 23, 2022
A simple and flexible Checked TextView or Checkable TextView

CheckableTextView Checkable TextView [KOTLIN] âš¡ A simple and flexible Checked TextView or Checkable TextView written in Kotlin âš¡ What's New Animation

null 110 Nov 20, 2022
Mentions-TextView - Make Mentions and hashtags clickable in Textview

Mentions Textview Custome Textview with Mentions and hashtags being clickable. D

null 2 Jan 9, 2022
Implementation of a TextView and all its direct/indirect subclasses with native support for the Roboto fonts, includes the brand new Roboto Slab fonts.

Android-RobotoTextView Implementation of a TextView and all its direct/indirect subclasses with native support for the Roboto fonts, includes the bran

Evgeny Shishkin 782 Nov 12, 2022
AutosizeEditText for Android is an extension of native EditText that offer a smooth auto scale text size.

AutoscaleEditText AutosizeEditText for Android is an extension of native EditText that offer a smooth auto scale text size. Latest Version How to use

Txus Ballesteros 354 Nov 28, 2022
This is based on an open source autosizing textview for Android.

SizeAdjustingTextView This is based on an open source autosizing textview for Android I found a few weeks ago. The initial approach didn't resize mult

Elliott Chenger 255 Dec 29, 2022
Form validation and feedback library for Android. Provides .setText for more than just TextView and EditText widgets. Provides easy means to validate with dependencies.

android-formidable-validation Form validation and feedback library for Android. Provides .setText for more than just TextView and EditText widgets. Pr

Linden 147 Nov 20, 2022
Simple way to create linked text, such as @username or #hashtag, in Android TextView and EditText

Simple Linkable Text Simple way to create link text, such as @username or #hashtag, in Android TextView and EditText Installation Gradle Add dependenc

Aditya Pradana Sugiarto 76 Nov 29, 2022
Customized and Expandable TextView

Customized and Expandable TextView Simple library to change the Textview as rectangle, circle and square shapes by adding one line of code in xml file

Raja Gopal 62 Sep 22, 2022
Animation effects to text, not really textview

HTextView Animation effects with custom font support to TextView see iOS Effects see Flutter Effects Screenshot type gif Scale Evaporate Fall Line Typ

hanks 5.5k Jan 5, 2023
Android's TextView that can expand/collapse like the Google Play's app description

ExpandableTextView ExpandableTextView is an Android library that allows developers to easily create an TextView which can expand/collapse just like th

Manabu S. 4k Dec 28, 2022
A library to show emoji in TextView, EditText (like WhatsApp) for Android

Discontinued This projected is discontinued. Please consider using other alternative, i.e EmojiCompat. Contact me if you want to continue working on a

Hieu Rocker 3.6k Jan 5, 2023
Android experiment showing a sinking TextView

Titanic is an Android experiment reproducing this effect.

Romain Piel 1.8k Dec 15, 2022
A Custom TextView with trim text

ReadMoreTextView A Custom TextView with trim text Download To add the ReadMoreTextView library to your Android Studio project, simply add the followin

Borja B. 1.7k Dec 29, 2022
Advanced Android TextView

Advanced Android TextView Companion app for my Advanced Android TextView talk, demostrating: Animated CompoundDrawable Text shadow Custom font Non-bre

Chiu-Ki Chan 1.2k Dec 9, 2022
A TextView that simulates the effect from the app Secret where the characters fade in/out at different speeds.

SecretTextView A TextView that simulates the effect from the app Secret where the characters fade in/out at different speeds. How To Use Use it just l

Matt Kula 611 Nov 7, 2022