开始中遇到,在ListView中想根据内容调整文字的颜色,完成了这种效果,先上图
这种效果时通过重写了TextView实现的,代码如下:
package com.example.demo.practice.ui;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* 报警红色文字
* 故障黄色文字
* 正常绿色文字
*/
public class WaterLevelTextView extends TextView {
private String mText;
private Paint mPaint;
private Rect mBound;
public WaterLevelTextView(Context context) {
super(context);
}
public WaterLevelTextView(Context context, AttributeSet attrs) {
super(context, attrs);
mText = (String) getText();
}
private void init() {
int mTextColor = Color.YELLOW;
int mTextSize = 80;
//排除空值异常
if(mText.equals("")){return;}
int s = Integer.parseInt(mText);
if (s > 60) {
mTextColor = Color.GREEN;
} else if(s<40) {
mTextColor = Color.RED;
}
mText=mText+"%";
mPaint = new Paint();
mPaint.setTextSize(mTextSize);
mPaint.setColor(mTextColor);
//获得绘制文本的宽和高
mBound = new Rect();
mPaint.getTextBounds(mText, 0, mText.length(), mBound);
}
@Override
public void setText(CharSequence text, BufferType type) {
mText = (String) text;
init();
this.invalidate();
super.setText(text, type);
}
@Override
protected void onDraw(Canvas canvas) {
//绘制文字
canvas.drawText(mText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint);
}
}