首页 > 解决方案 > 用于自动调整 TextView 大小的着色器 LinearGradient 未按预期工作

问题描述

我有这个自动调整TextView

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    android:id="@+id/rootView">

    <TextView
        android:id="@+id/my_text_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:gravity="bottom|center_horizontal"
        android:textAllCaps="true"
        android:textColor="#435f7b"
        android:maxLines="1"
        app:autoSizeTextType="uniform"
        app:autoSizeMinTextSize="10sp"
        app:autoSizeMaxTextSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />

</android.support.constraint.ConstraintLayout>

android:text以编程方式设置。

我需要申请LinearGradient

Shader shader = new LinearGradient(0, 0, 0, textView.getLineHeight()*1.1f, color1, color2, Shader.TileMode.REPEAT);
textView.getPaint().setShader(shader);

但它显然使用错误的尺寸来计算文本限制,所以它看起来像这样(例如在 Android 6.0 上):

在此处输入图像描述

布局用作Fragment,使用FragmentStatePagerAdapter 和PagerAdapter。

如何使它起作用?它可以在没有自动调整大小的情况下在其他 s 集上正常工作,TextView但只能textSizeFragments 中使用 , 。

非常感谢!

标签: androidtext

解决方案


这是您根据 EugenPechanec 的评论寻找的代码。

TextView textView = findViewById(R.id.my_text_view);
textView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        int color1 = Color.RED; // Or whatever color you need.
        int color2 = Color.BLUE;
        TextView tv = (TextView) v;

        Shader shader = new LinearGradient(0, 0, 0, tv.getLineHeight() * 1.1f, color1, color2, Shader.TileMode.REPEAT);
        tv.getPaint().setShader(shader);
    }
});

推荐阅读