TextView autoSizeTextType 在动态文本视图中不起作用

TextView autoSizeTextType not working in dynamic textview

我正在尝试以编程方式创建 textView 并在其上设置高度、设置宽度和自动文本大小。 textview 工作正常,但自动文本大小不起作用! 请帮助我。

  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);

及其我的 xml 代码

<?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>

使用支持库中的 AppcompatTextView:

TextView textView = new AppCompatTextView(MainActivity.this);

或者如果这不起作用:

AppCompatTextView textView = new AppCompatTextView(MainActivity.this);

这样做的原因是,当您在 XML 中定义视图并且您使用的是 AppCompat 上下文(如 AppCompatActivity)时,膨胀的 TextView 不是 class 中的 TextView Android 框架,但 TextView 子class 调用了 AppCompatTextView。对于其他几个小部件也是如此。您可以检查 this 以查看其他几个被覆盖的小部件。