android - 用于自动调整 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
但只能textSize
在Fragment
s 中使用 , 。
非常感谢!
解决方案
这是您根据 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);
}
});
推荐阅读
- python - DRF - 创建 Viewset Mixin/Baseclass 以继承 viewset-action
- javascript - 如何使用 Vue-plugin-load-script
- php - 如何使用 WP_Query 将帖子名称发送到选择自定义字段插件中?
- c++ - 如何从另一个文件/类访问/更新某个头文件中的映射
- angular - Angular 材质选项卡中动态加载的内容
- ffmpeg - ffmpeg:如何强制 divx5 标签?
- sql - 在 R 中提取 XML sqlQuery 问题 - 查询 Clob 列
- azure-cosmosdb - 使用 .NET SDK 未正确设置空间索引类型
- python - 如何在xhtml2pdf中将阿拉伯字符导出为pdf?
- android - iOS 和 Android 上的最大并发蓝牙 LE 设备?