Android Custom TextView Sliding Unlock Highlight Text
- 2021-08-31 09:06:49
- OfStack
The following 1 code to share Android custom TextView to achieve sliding unlocking highlight text effect, the specific code is as follows:
public class HightLightTextView extends TextView {
// Storage view Width of
private int mTextViewWidth = 0;
// Paintbrush
private Paint mPaint;
// Linear rendering
private LinearGradient mLinearGradient;
// Storage transformed matrix
private Matrix matrix;
// Moving distance
private int mTranslateX = 0;
// Construction method
public HightLightTextView(Context context) {
this(context, null);
}
public HightLightTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public HightLightTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* view Call procedure of : Construction method ->onFinishInflate->onSizeChanged->onDraw
*/
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// Get view Initial properties such as the width of the, initialization brush, and so on
if (mTextViewWidth == 0) {
mTextViewWidth = getMeasuredWidth();
// If the width is greater than 0 Initializes the
if (mTextViewWidth > 0) {
// Initialize brush
mPaint = getPaint();
// Linear rendering
mLinearGradient = new LinearGradient(0, getMeasuredHeight(), mTextViewWidth, 0,
new int[]{0X55FFFFFF, 0XFFFFFFFF, 0X55FFFFFF},
new float[]{0, 0.5f, 1}, Shader.TileMode.CLAMP);
mPaint.setShader(mLinearGradient);
matrix = new Matrix();
}
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (matrix != null) {
mTranslateX += mTextViewWidth / 10;
// If you move more than twice the width, start moving again
if (mTranslateX > 2 * mTextViewWidth) {
mTranslateX = -mTextViewWidth;
}
// Translation matrix
matrix.setTranslate(mTranslateX, 0);
// Set linearly varying matrix
mLinearGradient.setLocalMatrix(matrix);
// Delay 50ms Redraw ( Will be called again when redrawing onDraw)
postInvalidateDelayed(50);
}
}
}
Additional:
Android TextView Specify Key Highlight
There is this requirement in the project. I searched one on the Internet, and there are many methods. Here, I choose a simple and verified available method, and record it for later reference.
TextView tv = (TextView) findViewById(R.id.hello);
SpannableString s = new SpannableString(getResources().getString(R.string.linkify));
Pattern p = Pattern.compile("abc");
Matcher m = p.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
s.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
tv.setText(s);
Quite simply, tv is the TextView control, s is the string to display, and "abc" is the keyword to highlight.