Android programmer
Android programmer

Reputation: 19

TextView autoSizeTextType not working in dynamic textview

I am trying to create textView Programically and setHeight ,setWidth and auto text size on it. textview is working good but auto text size not working! please help me.

  AbsoluteLayout absoluteLayout = findViewById(R.id.absoluteLayout);

    TextView textView = new TextView(MainActivity.this);
    textView.setText("Hi Ali");


    textView.setWidth(300);
    textView.setHeight(100);

    textView.setX(100);
    textView.setY(40);
    TextViewCompat.setAutoSizeTextTypeWithDefaults(textView, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);

    //border
    GradientDrawable gd = new GradientDrawable();
    gd.setStroke(2, 0xFF000000);
    gd.setCornerRadius(5);
    textView.setBackground(gd);

    absoluteLayout.addView(textView);

and its my xml code

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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">


    <AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/absoluteLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

Upvotes: 0

Views: 224

Answers (1)

owsega
owsega

Reputation: 96

Use AppcompatTextView from the Support Library:

TextView textView = new AppCompatTextView(MainActivity.this);

or if that doesn't work:

AppCompatTextView textView = new AppCompatTextView(MainActivity.this);

The reason this works is that when you define views in XML and you are using an AppCompat context (like AppCompatActivity), then the TextView that gets inflated is not the TextView class in the Android framework, but the TextView subclass called AppCompatTextView. This is true for several other widgets. You can check this to see several other widgets that get overridden.

Upvotes: 1

Related Questions