【问题标题】:TextView autoSizeTextType not working in dynamic textviewTextView autoSizeTextType 在动态文本视图中不起作用
【发布时间】:2019-02-04 12:04:11
【问题描述】:

我正在尝试以编程方式创建 textView 并在其上设置 setHeight、setWidth 和自动文本大小。 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>

【问题讨论】:

    标签: android textview


    【解决方案1】:

    使用支持库中的 AppcompatTextView:

    TextView textView = new AppCompatTextView(MainActivity.this);
    

    或者如果这不起作用:

    AppCompatTextView textView = new AppCompatTextView(MainActivity.this);
    

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

    【讨论】:

      猜你喜欢
      • 2021-10-22
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多