package com.trs.nmip.common.ui.news.list.view;
import android.content.Context;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.util.AttributeSet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* <pre>
* Created by zhuguohui
* Date: 2023/4/19
* Time: 17:36
* Desc:如果内容超过xml中maxLength属性定义的文字数量时,会被添加省略号
* </pre>
*/
public class MaxLengthTextView extends androidx.appcompat.widget.AppCompatTextView {
public MaxLengthTextView(@NonNull Context context) {
super(context);
}
public MaxLengthTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
public void setFilters(InputFilter[] filters) {
replaceLengthFilter(filters);
super.setFilters(filters);
}
private InputFilter[] replaceLengthFilter(InputFilter[] filters) {
for (int i = 0; i < filters.length; i++) {
InputFilter filter = filters[i];
if (filter instanceof InputFilter.LengthFilter) {
filters[i] = new MyLengthFilter((InputFilter.LengthFilter) filter);
break;
}
}
return filters;
}
private static class MyLengthFilter implements InputFilter {
InputFilter.LengthFilter inputFilter;
public MyLengthFilter(InputFilter.LengthFilter inputFilter) {
this.inputFilter = inputFilter;
}
public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
int dstart, int dend) {
int length = source.length();
CharSequence sequence = inputFilter.filter(source, start, end, dest, dstart, dend);
if(sequence!=null) {
int length1 = sequence.length();
if (length1 != length) {
//表示有裁剪
if (sequence instanceof SpannableStringBuilder) {
SpannableStringBuilder builder= (SpannableStringBuilder) sequence;
builder.append("...");
return builder;
}
if(sequence instanceof SpannableString ){
SpannableString spannableString= (SpannableString) sequence;
SpannableStringBuilder builder=new SpannableStringBuilder(spannableString);
builder.append("...");
return builder;
}
}
}
return sequence;
}
}
}
MaxLengthTextView 如果内容超过xml中maxLength属性定义的文字数量时,会被添加省略号
于 2024-01-09 15:27:49 首次发布
本文介绍了如何在Android的MaxLengthTextView组件中,当内容超过XML定义的maxLength属性值时,自动添加省略号的自定义输入过滤器实现。
摘要由CSDN通过智能技术生成