繁体   English   中英

TextView autoSizeTextType在动态Textview中不起作用

[英]TextView autoSizeTextType not working in dynamic textview

我正在尝试以编程方式创建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>

使用支持库中的AppcompatTextView:

TextView textView = new AppCompatTextView(MainActivity.this);

或如果不起作用:

AppCompatTextView textView = new AppCompatTextView(MainActivity.this);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM