一、自定义编辑框
效果图:
主要的代码为:
class EditLayout @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
private var editTitle: String
private var editContent: String
private var editType: Int
private var isMust: Boolean
private var tvLabelEdit: TextView
private var ivMustEdit: ImageView
private var etEdit: EditText
private var editable: Boolean
init {
LayoutInflater.from(context).inflate(R.layout.layout_edit, this)
tvLabelEdit = findViewById(R.id.tv_label_edit)
ivMustEdit = findViewById(R.id.iv_must_edit)
etEdit = findViewById(R.id.et_edit)
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.EditLayout)
editTitle = typedArray.getString(R.styleable.EditLayout_editTitle) ?: ""
editContent = typedArray.getString(R.styleable.EditLayout_editContent) ?: ""
editType = typedArray.getInt(R.styleable.EditLayout_editType, 1)
editable = typedArray.getBoolean(R.styleable.EditLayout_editable, true)
isMust = typedArray.getBoolean(R.styleable.EditLayout_isMust, false)
typedArray.recycle();
applyLabel()
applyIv()
applyEdit()
}
private fun applyLabel() {
tvLabelEdit.text = editTitle
etEdit.setText(editContent)
}
private fun applyIv() {
ivMustEdit.visibility = if (isMust) View.VISIBLE else View.GONE
}
private fun applyEdit() {
etEdit.inputType = when (editType) {
1 -> InputType.TYPE_CLASS_TEXT
2 -> InputType.TYPE_CLASS_NUMBER
else -> InputType.TYPE_CLASS_TEXT
}
etEdit.isEnabled = editable
}
fun getEditText(): EditText {
return etEdit
}
fun getInputText(): String {
return etEdit.text.toString()
}
fun setInputText(input: String) {
etEdit.setText(input)
}
}
使用3个原生控件组合而成,具体的代码可以到这里下载:
https://download.youkuaiyun.com/download/wy313622821/88467564
二、悬浮窗
主要的代码:
@SuppressLint("ClickableViewAccessibility")
class FloatWindow(private val mContext: Context) : LifecycleService() {
private var floatRootView: View? = null
private val mBinding: WindowFloatBinding by lazy {
DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.window_float, null, false)
}
private val windowManager: WindowManager by lazy {
mContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
}
private val layoutParams: WindowManager.LayoutParams by lazy {
WindowManager.LayoutParams().apply {
width = WindowManager.LayoutParams.WRAP_CONTENT
height = WindowManager.LayoutParams.WRAP_CONTENT
flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
gravity = Gravity.END
type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
} else {
WindowManager.LayoutParams.TYPE_PHONE
}
}
}
private var mAllDoorListen: () -> Unit = {}
init {
floatRootView = mBinding.root
floatRootView?.setOnTouchListener(ItemViewTouchListener(layoutParams, windowManager))
floatRootView?.setBackgroundColor(Color.TRANSPARENT)
val outMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(outMetrics)
layoutParams.format = PixelFormat.TRANSPARENT
mBinding.tvOpenDoorAll.setOnClickListener {
}
mBinding.clLeft.setOnClickListener {
Log.e("TAG", "缩小")
indenteOrExpand()
}
}
/** 缩进或者展开 **/
private fun indenteOrExpand() {
mBinding.llContentOperate.let {
if (it.visibility == View.GONE) {
it.visibility = View.VISIBLE
mBinding.ivIndenteExpand.setImageResource(R.mipmap.ic_indentation_float)
} else {
it.visibility = View.GONE
mBinding.ivIndenteExpand.setImageResource(R.mipmap.ic_expand_float)
}
}
}
inner class ItemViewTouchListener(
private val wl: WindowManager.LayoutParams,
private val windowManager: WindowManager
) : View.OnTouchListener {
// private var x = 0
private var y = 0
override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
Log.e("TAG", "位置改变")
when (motionEvent.action) {
MotionEvent.ACTION_DOWN -> {
// x = motionEvent.rawX.toInt()
y = motionEvent.rawY.toInt()
}
MotionEvent.ACTION_MOVE -> {
// val nowX = motionEvent.rawX.toInt()
val nowY = motionEvent.rawY.toInt()
// val movedX = nowX - x
val movedY = nowY - y
// x = nowX
y = nowY
wl.apply {
// x += movedX
y += movedY
}
//更新悬浮球控件位置
windowManager.updateViewLayout(view, wl)
}
else -> {
}
}
return false
}
}
/** 悬浮窗显示 */
fun show() {
windowManager.addView(floatRootView, layoutParams)
}
/** 悬浮窗移除 */
fun remove() {
floatRootView?.let {
windowManager.removeViewImmediate(it)
floatRootView = null
}
}
/** 设置全部开启按钮监听 */
fun setOpenAllListener(mListen: () -> Unit) {
mAllDoorListen = mListen
}
}
详细的代码请到这里下载:https://download.youkuaiyun.com/download/wy313622821/88468147
三、自定义进度条
package ryb.medicine.delegate_weituo.customui;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import ryb.medicine.delegate_weituo.R;
public class CircleProgress extends View {
private static final String TAG = CircleProgress.class.getSimpleName();
private Context mContext;
//默认大小
private int mDefaultSize;
//是否开启抗锯齿
private boolean antiAlias;
//绘制提示
private TextPaint mHintPaint;
private CharSequence mHint;
private int mHintColor;
private float mHintSize;
private float mHintOffset;
//绘制单位
private TextPaint mUnitPaint;
private CharSequence mUnit;
private int mUnitColor;
private float mUnitSize;
private float mUnitOffset;
//绘制数值
private TextPaint mValuePaint;
private float mValue;
private float mMaxValue;
private float mValueOffset;
private int mPrecision;
private String mPrecisionFormat;
private int mValueColor;
private float mValueSize;
//绘制圆弧
private Paint mArcPaint;
private float mArcWidth;
private float mStartAngle, mSweepAngle;
private RectF mRectF;
//当前进度,[0.0f,1.0f]
private float mPercent;
//动画时间
private long mAnimTime;
//属性动画
private ValueAnimator mAnimator;
//绘制背景圆弧
private Paint mBgArcPaint;
private int mBgArcColor;
private int mArcColor;
private float mBgArcWidth;
//圆心坐标,半径
private Point mCenterPoint;
private float mRadius;
private float mTextOffsetPercentInRadius;
private int mArcCenterX;
// 内部虚线的外部半径
private float mExternalDottedLineRadius;
// 内部虚线的内部半径
private float mInsideDottedLineRadius;
// 线条数
private int mDottedLineCount = 100;
// 圆弧跟虚线之间的距离
private int mLineDistance = 20;
// 线条宽度
private float mDottedLineWidth = 40;
//是否使用渐变
protected boolean useGradient=true;
//前景色起始颜色
private int foreStartColor;
//前景色结束颜色
private int foreEndColcor;
protected int mWidth;
protected int mHeight;
public CircleProgress(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
mContext = context;
mDefaultSize = dipToPx(mContext, 150);
mAnimator = new ValueAnimator();
mRectF = new RectF();
mCenterPoint = new Point();
initAttrs(attrs);
initPaint();
setValue(mValue);
}
private void initAttrs(AttributeSet attrs) {
TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar);
antiAlias = typedArray.getBoolean(R.styleable.CircleProgressBar_antiAlias, true);
mHint = typedArray.getString(R.styleable.CircleProgressBar_hint);
mHintColor = typedArray.getColor(R.styleable.CircleProgressBar_hintColor, Color.BLACK);
mHintSize = typedArray.getDimension(R.styleable.CircleProgressBar_hintSize, 15);
mValue = typedArray.getFloat(R.styleable.CircleProgressBar_value, 50);
mMaxValue = typedArray.getFloat(R.styleable.CircleProgressBar_maxValue, 50);
//内容数值精度格式
mPrecision = typedArray.getInt(R.styleable.CircleProgressBar_precision, 0);
mPrecisionFormat = getPrecisionFormat(mPrecision);
mValueColor = typedArray.getColor(R.styleable.CircleProgressBar_valueColor, Color.BLACK);
mValueSize = typedArray.getDimension(R.styleable.CircleProgressBar_valueSize, 15);
mUnit = typedArray.getString(R.styleable.CircleProgressBar_unit);
mUnitColor = typedArray.getColor(R.styleable.CircleProgressBar_unitColor, Color.BLACK);
mUnitSize = typedArray.getDimension(R.styleable.CircleProgressBar_unitSize, 30);
mArcWidth = typedArray.getDimension(R.styleable.CircleProgressBar_arcWidth, 15);
mStartAngle = typedArray.getFloat(R.styleable.CircleProgressBar_startAngle, 270);
mSweepAngle = typedArray.getFloat(R.styleable.CircleProgressBar_sweepAngle, 360);
mBgArcColor = typedArray.getColor(R.styleable.CircleProgressBar_bgArcColor, Color.WHITE);
mArcColor = typedArray.getColor(R.styleable.CircleProgressBar_arcColors, Color.RED);
mBgArcWidth = typedArray.getDimension(R.styleable.CircleProgressBar_bgArcWidth, 15);
mTextOffsetPercentInRadius = typedArray.getFloat(R.styleable.CircleProgressBar_textOffsetPercentInRadius, 0.33f);
mAnimTime = typedArray.getInt(R.styleable.CircleProgressBar_animTime, 50);
mDottedLineCount = typedArray.getInteger(R.styleable.CircleProgressBar_dottedLineCount, mDottedLineCount);
mLineDistance = typedArray.getInteger(R.styleable.CircleProgressBar_lineDistance, mLineDistance);
mDottedLineWidth = typedArray.getDimension(R.styleable.CircleProgressBar_dottedLineWidth, mDottedLineWidth);
foreStartColor = typedArray.getColor(R.styleable.CircleProgressBar_foreStartColor, Color.BLUE);
foreEndColcor = typedArray.getColor(R.styleable.CircleProgressBar_foreEndColor, Color.BLUE);
typedArray.recycle();
}
private void initPaint() {
mHintPaint = new TextPaint();
// 设置抗锯齿,会消耗较大资源,绘制图形速度会变慢。
mHintPaint.setAntiAlias(antiAlias);
// 设置绘制文字大小
mHintPaint.setTextSize(mHintSize);
// 设置画笔颜色
mHintPaint.setColor(mHintColor);
// 从中间向两边绘制,不需要再次计算文字
mHintPaint.setTextAlign(Paint.Align.CENTER);
mValuePaint = new TextPaint();
mValuePaint.setAntiAlias(antiAlias);
mValuePaint.setTextSize(mValueSize);
mValuePaint.setColor(mValueColor);
// 设置Typeface对象,即字体风格,包括粗体,斜体以及衬线体,非衬线体等
mValuePaint.setTypeface(Typeface.DEFAULT_BOLD);
mValuePaint.setTextAlign(Paint.Align.CENTER);
mUnitPaint = new TextPaint();
mUnitPaint.setAntiAlias(antiAlias);
mUnitPaint.setTextSize(mUnitSize);
mUnitPaint.setColor(mUnitColor);
mUnitPaint.setTextAlign(Paint.Align.CENTER);
mArcPaint = new Paint();
mArcPaint.setAntiAlias(antiAlias);
// 设置画笔的样式,为FILL,FILL_OR_STROKE,或STROKE
mArcPaint.setStyle(Paint.Style.STROKE);
// 设置画笔粗细
mArcPaint.setStrokeWidth(mArcWidth);
// 当画笔样式为STROKE或FILL_OR_STROKE时,设置笔刷的图形样式,如圆形样式
// Cap.ROUND(圆形样式)或Cap.SQUARE(方形样式)
mArcPaint.setStrokeCap(Paint.Cap.ROUND);
mBgArcPaint = new Paint();
mBgArcPaint.setAntiAlias(antiAlias);
mBgArcPaint.setColor(mBgArcColor);
mBgArcPaint.setStyle(Paint.Style.STROKE);
mBgArcPaint.setStrokeWidth(mBgArcWidth);
mBgArcPaint.setStrokeCap(Paint.Cap.ROUND);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(measureView(widthMeasureSpec, mDefaultSize),
measureView(heightMeasureSpec, mDefaultSize));
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mArcCenterX = (int) (w / 2.f);
Log.d(TAG, "onSizeChanged: w = " + w + "; h = " + h + "; oldw = " + oldw + "; oldh = " + oldh);
//求圆弧和背景圆弧的最大宽度
float maxArcWidth = Math.max(mArcWidth, mBgArcWidth);
//求最小值作为实际值
int minSize = Math.min(w - getPaddingLeft() - getPaddingRight() - 2 * (int) maxArcWidth,
h - getPaddingTop() - getPaddingBottom() - 2 * (int) maxArcWidth);
//减去圆弧的宽度,否则会造成部分圆弧绘制在外围
mRadius = minSize / 2;
//获取圆的相关参数
mCenterPoint.x = w / 2;
mCenterPoint.y = h / 2;
//绘制圆弧的边界
mRectF.left = mCenterPoint.x - mRadius - maxArcWidth / 2;
mRectF.top = mCenterPoint.y - mRadius - maxArcWidth / 2;
mRectF.right = mCenterPoint.x + mRadius + maxArcWidth / 2;
mRectF.bottom = mCenterPoint.y + mRadius + maxArcWidth / 2;
//计算文字绘制时的 baseline
//由于文字的baseline、descent、ascent等属性只与textSize和typeface有关,所以此时可以直接计算
//若value、hint、unit由同一个画笔绘制或者需要动态设置文字的大小,则需要在每次更新后再次计算
mValueOffset = mCenterPoint.y + getBaselineOffsetFromY(mValuePaint);
mHintOffset = mCenterPoint.y - mRadius * mTextOffsetPercentInRadius + getBaselineOffsetFromY(mHintPaint);
mUnitOffset = mCenterPoint.y + mRadius * mTextOffsetPercentInRadius + getBaselineOffsetFromY(mUnitPaint);
if (useGradient) {
LinearGradient gradient = new LinearGradient(0, 0, w, h, foreEndColcor, foreStartColor, Shader.TileMode.CLAMP);
mArcPaint.setShader(gradient);
} else {
mArcPaint.setColor(mArcColor);
}
Log.d(TAG, "onSizeChanged: 控件大小 = " + "(" + w + ", " + h + ")"
+ "圆心坐标 = " + mCenterPoint.toString()
+ ";圆半径 = " + mRadius
+ ";圆的外接矩形 = " + mRectF.toString());
// 虚线的外部半径
mExternalDottedLineRadius = (int) (mRectF.width() / 2)+mLineDistance;
// 虚线的内部半径
mInsideDottedLineRadius = mExternalDottedLineRadius - mDottedLineWidth;
}
private float getBaselineOffsetFromY(Paint paint) {
Paint.FontMetrics fontMetrics = paint.getFontMetrics();
return ((Math.abs(fontMetrics.ascent) - fontMetrics.descent))/ 2;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawText(canvas);
drawArc(canvas);
}
/**
* 绘制内容文字
*
* @param canvas
*/
private void drawText(Canvas canvas) {
canvas.drawText(String.format(mPrecisionFormat, mValue), mCenterPoint.x, mValueOffset, mValuePaint);
if (mHint != null) {
canvas.drawText(mHint.toString(), mCenterPoint.x, mHintOffset, mHintPaint);
}
if (mUnit != null) {
canvas.drawText(mUnit.toString(), mCenterPoint.x, mUnitOffset, mUnitPaint);
}
}
private void drawArc(Canvas canvas) {
// 绘制背景圆弧
// 从进度圆弧结束的地方开始重新绘制,优化性能
canvas.save();
// 360 * Math.PI / 180
float evenryDegrees = (float) (2.0f * Math.PI / mDottedLineCount);
float startDegress = (float) (135 * Math.PI / 180);
float endDegress = (float) (225 * Math.PI / 180);
for (int i = 0; i < mDottedLineCount; i++) {
float degrees = i * evenryDegrees;
// 过滤底部90度的弧长
if (degrees > startDegress && degrees < endDegress) {
continue;
}
float startX = mArcCenterX + (float) Math.sin(degrees) * mInsideDottedLineRadius;
float startY = mArcCenterX - (float) Math.cos(degrees) * mInsideDottedLineRadius;
float stopX = mArcCenterX + (float) Math.sin(degrees) * mExternalDottedLineRadius;
float stopY = mArcCenterX - (float) Math.cos(degrees) * mExternalDottedLineRadius;
canvas.drawLine(startX, startY, stopX, stopY, mBgArcPaint);
}
canvas.rotate(mStartAngle, mCenterPoint.x, mCenterPoint.y);
// 第一个参数 oval 为 RectF 类型,即圆弧显示区域
// startAngle 和 sweepAngle 均为 float 类型,分别表示圆弧起始角度和圆弧度数
// 3点钟方向为0度,顺时针递增
// 如果 startAngle < 0 或者 > 360,则相当于 startAngle % 360
// useCenter:如果为True时,在绘制圆弧时将圆心包括在内,通常用来绘制扇形
float currentAngle = mSweepAngle * mPercent;
canvas.drawArc(mRectF, 2, currentAngle, false, mArcPaint);
canvas.restore();
}
public boolean isAntiAlias() {
return antiAlias;
}
public CharSequence getHint() {
return mHint;
}
public void setHint(CharSequence hint) {
mHint = hint;
}
public CharSequence getUnit() {
return mUnit;
}
public void setUnit(CharSequence unit) {
mUnit = unit;
}
public float getValue() {
return mValue;
}
/**
* 设置当前值
*
* @param value
*/
public void setValue(float value) {
if (value > mMaxValue) {
value = mMaxValue;
}
float start = mPercent;
float end = value / mMaxValue;
startAnimator(start, end, mAnimTime);
}
private void startAnimator(float start, float end, long animTime) {
mAnimator = ValueAnimator.ofFloat(start, end);
mAnimator.setDuration(animTime);
mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mPercent = (float) animation.getAnimatedValue();
mValue = mPercent * mMaxValue;
// if (BuildConfig.DEBUG) {
// Log.d(TAG, "onAnimationUpdate: percent = " + mPercent
// + ";currentAngle = " + (mSweepAngle * mPercent)
// + ";value = " + mValue);
// }
invalidate();
}
});
mAnimator.start();
}
/**
* 获取最大值
*
* @return
*/
public float getMaxValue() {
return mMaxValue;
}
/**
* 设置最大值
*
* @param maxValue
*/
public void setMaxValue(float maxValue) {
mMaxValue = maxValue;
}
/**
* 获取精度
*
* @return
*/
public int getPrecision() {
return mPrecision;
}
public void setPrecision(int precision) {
mPrecision = precision;
mPrecisionFormat = getPrecisionFormat(precision);
}
public long getAnimTime() {
return mAnimTime;
}
public void setAnimTime(long animTime) {
mAnimTime = animTime;
}
/**
* 重置
*/
public void reset() {
startAnimator(mPercent, 0.0f, 1000L);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
//释放资源
}
/**
* 测量 View
*
* @param measureSpec
* @param defaultSize View 的默认大小
* @return
*/
private static int measureView(int measureSpec, int defaultSize) {
int result = defaultSize;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
return result;
}
/**
* dip 转换成px
*
* @param dip
* @return
*/
public static int dipToPx(Context context, float dip) {
float density = context.getResources().getDisplayMetrics().density;
return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1));
}
/**
* 获取数值精度格式化字符串
*
* @param precision
* @return
*/
public static String getPrecisionFormat(int precision) {
return "%." + precision + "f";
}
}
attrs.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 是否开启抗锯齿 -->
<attr name="antiAlias" format="boolean" />
<!-- 圆弧起始角度,3点钟方向为0,顺时针递增,小于0或大于360进行取余 -->
<attr name="startAngle" format="float" />
<!-- 圆弧度数 -->
<attr name="sweepAngle" format="float" />
<!-- 设置动画时间 -->
<attr name="animTime" format="integer" />
<!-- 绘制内容的数值 -->
<attr name="maxValue" format="float" />
<attr name="value" format="float" />
<!-- 绘制内容的单位 -->
<attr name="unit" format="string|reference" />
<attr name="unitSize" format="dimension" />
<attr name="unitColor" format="color|reference" />
<!-- 绘制内容相应的提示语 -->
<attr name="hint" format="string|reference" />
<attr name="hintSize" format="dimension" />
<attr name="hintColor" format="color|reference" />
<!-- 精度,默认为0 -->
<attr name="precision" format="integer" />
<attr name="valueSize" format="dimension" />
<attr name="valueColor" format="color|reference" />
<!-- 背景圆弧颜色,默认白色 -->
<attr name="bgArcColor" format="color|reference" />
<!-- 圆弧宽度 -->
<attr name="arcWidth" format="dimension" />
<!-- 圆弧颜色, -->
<attr name="arcColors" format="color|reference" />
<!-- 文字的偏移量 相对于圆半径而言,默认三分之一 -->
<attr name="textOffsetPercentInRadius" format="float" />
<!-- 背景圆弧宽度 -->
<attr name="bgArcWidth" format="dimension" />
<!-- 线条数 -->
<attr name="dottedLineCount" format="integer" />
<!-- 圆弧跟虚线之间的距离 -->
<attr name="lineDistance" format="integer" />
<!-- 线条宽度 -->
<attr name="dottedLineWidth" format="dimension" />
<!-- 进度条的前景色 起始颜色-->
<attr name="foreStartColor" format="color" />
<!-- 进度条的前景色 结束颜色-->
<attr name="foreEndColor" format="color" />
<declare-styleable name="CircleProgressBar">
<attr name="antiAlias" />
<attr name="startAngle" />
<attr name="sweepAngle" />
<attr name="animTime" />
<attr name="maxValue" />
<attr name="value" />
<attr name="unit" />
<attr name="unitSize" />
<attr name="unitColor" />
<attr name="hint" />
<attr name="hintSize" />
<attr name="hintColor" />
<attr name="precision" />
<attr name="valueSize" />
<attr name="valueColor" />
<attr name="bgArcColor" />
<attr name="arcWidth" />
<attr name="arcColors" />
<attr name="textOffsetPercentInRadius" />
<attr name="bgArcWidth" />
<attr name="dottedLineCount" />
<attr name="lineDistance" />
<attr name="dottedLineWidth" />
<attr name="foreStartColor" />
<attr name="foreEndColor" />
</declare-styleable>
</resources>
在activity.xml文件里使用
<ryb.medicine.delegate_weituo.customui.CircleProgress
android:id="@+id/circle_progress"
android:layout_width="260dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
app:antiAlias="true"
app:arcWidth="15dp"
app:bgArcColor="@android:color/darker_gray"
app:bgArcWidth="2dp"
app:dottedLineWidth="12dp"
app:foreEndColor="#F4F200"
app:foreStartColor="#FE6615"
app:hintSize="15dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.498"
app:maxValue="100"
app:startAngle="135"
app:sweepAngle="270"
app:textOffsetPercentInRadius="0.5"
app:unit=""
app:unitColor="@android:color/darker_gray"
app:unitSize="15dp"
app:value="0"
app:valueColor="#FFCC1E"
app:valueSize="80dp"
tools:ignore="MissingClass" />
设置值
findViewById<CircleProgress>(R.id.circle_progress).value = 75f
四、带删除按钮的输入框
/**
* 创建时间:2023/10/24
*
* @author RexHuang
* 类说明:自定义带删除按钮的EditText
*/
@SuppressLint("AppCompatCustomView")
public class ClearEditText extends EditText implements View.OnFocusChangeListener,
TextWatcher {
//EditText右侧的删除按钮
private Drawable mClearDrawable;
private Drawable mDefaultDrawableEnd;
private boolean hasFocus;
public ClearEditText(Context context) {
this(context, null);
}
public ClearEditText(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.editTextStyle);
}
public ClearEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ClearEditText);
mClearDrawable = typedArray.getDrawable(R.styleable.ClearEditText_drawableClear);
if (mClearDrawable == null) {
mClearDrawable = getResources().getDrawable(R.drawable.ic_round_clear_24, null);
}
mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(),
mClearDrawable.getIntrinsicHeight());
typedArray.recycle();
init();
}
private void init() {
// 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片,获取图片的顺序是左上右下(0,1,2,3,)
mDefaultDrawableEnd = getCompoundDrawables()[2];
if (mDefaultDrawableEnd == null) {
mDefaultDrawableEnd = getCompoundDrawablesRelative()[2];
}
// 默认设置隐藏图标
setClearIconVisible(false);
// 设置焦点改变的监听
setOnFocusChangeListener(this);
// 设置输入框里面内容发生改变的监听
addTextChangedListener(this);
}
/* @说明:isInnerWidth, isInnerHeight为ture,触摸点在删除图标之内,则视为点击了删除图标
* event.getX() 获取相对应自身左上角的X坐标
* event.getY() 获取相对应自身左上角的Y坐标
* getWidth() 获取控件的宽度
* getHeight() 获取控件的高度
* getTotalPaddingRight() 获取删除图标左边缘到控件右边缘的距离
* getPaddingRight() 获取删除图标右边缘到控件右边缘的距离
* isInnerWidth:
* getWidth() - getTotalPaddingRight() 计算删除图标左边缘到控件左边缘的距离
* getWidth() - getPaddingRight() 计算删除图标右边缘到控件左边缘的距离
* isInnerHeight:
* distance 删除图标顶部边缘到控件顶部边缘的距离
* distance + height 删除图标底部边缘到控件顶部边缘的距离
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (getCompoundDrawables()[2] != null) {
int x = (int) event.getX();
int y = (int) event.getY();
Rect rect = getCompoundDrawables()[2].getBounds();
int height = rect.height();
int distance = (getHeight() - height) / 2;
boolean isInnerWidth = x > (getWidth() - getTotalPaddingRight()) && x < (getWidth() - getPaddingRight());
boolean isInnerHeight = y > distance && y < (distance + height);
if (isInnerWidth && isInnerHeight) {
this.setText("");
}
}
}
return super.onTouchEvent(event);
}
/**
* 当ClearEditText焦点发生变化的时候,
* 输入长度为零,隐藏删除图标,否则,显示删除图标
*/
@Override
public void onFocusChange(View v, boolean hasFocus) {
this.hasFocus = hasFocus;
if (hasFocus) {
setClearIconVisible(getText().length() > 0);
} else {
setClearIconVisible(false);
}
}
protected void setClearIconVisible(boolean visible) {
Drawable right = visible ? mClearDrawable : mDefaultDrawableEnd;
Drawable start = getCompoundDrawables()[0] != null ? getCompoundDrawables()[0] : getCompoundDrawablesRelative()[0];
Drawable end = getCompoundDrawables()[3] != null ? getCompoundDrawables()[3] : getCompoundDrawablesRelative()[3];
setCompoundDrawables(start,
getCompoundDrawables()[1], right, end);
}
@Override
public void onTextChanged(CharSequence s, int start, int count, int after) {
if (hasFocus) {
setClearIconVisible(s.length() > 0);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
}
在activity中使用
<LinearLayout
android:id="@+id/ll_search"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="10dp"
android:layout_marginHorizontal="10dp"
android:background="@drawable/shape_rect_condition_bg_22"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="10dp">
<ImageView
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_gravity="center_vertical"
android:layout_marginStart="10dp"
android:src="@drawable/ic_search" />
<!--搜索框-->
<ryb.medicine.delegate_weituo.customui.ClearEditText
android:id="@+id/edt_input"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_marginHorizontal="8dp"
android:layout_weight="1"
android:background="@null"
android:hint=" 请输入耗材名称"
android:imeOptions="actionSearch"
android:paddingVertical="10dp"
android:singleLine="true"
android:textColorHint="#A9B0B7"
android:textSize="14sp" />
</LinearLayout>
attrs.xml的代码:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ClearEditText">
<attr name="drawableClear" format="reference" />
</declare-styleable>
</resources>
baseline_clear_24.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="10dp"
android:height="10dp"
android:tint="@android:color/white"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="@android:color/white"
android:pathData="M19,6.41L17.59,5 12,10.59 6.41,5 5,6.41 10.59,12 5,17.59 6.41,19 12,13.41 17.59,19 19,17.59 13.41,12z" />
</vector>
ic_round_clear_24.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="#A5ABB4"/> <!-- Background color of the circle -->
<size android:width="15dp" android:height="15dp"/> <!-- Size of the circle -->
</shape>
</item>
<item android:drawable="@drawable/baseline_clear_24" android:gravity="center"/>
</layer-list>
ic_search.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="26dp"
android:height="26dp"
android:viewportWidth="66"
android:viewportHeight="66">
<path
android:pathData="M49.305,45.129L64.845,60.669L64.845,60.669C65.998,61.822 65.998,63.691 64.845,64.845C63.692,65.998 61.823,65.998 60.67,64.845L45.13,49.304C34.244,58.104 18.246,57.441 8.123,47.319C-2.705,36.491 -2.708,18.939 8.115,8.115C18.94,-2.708 36.492,-2.705 47.319,8.123C57.441,18.245 58.104,34.244 49.305,45.129L49.305,45.129ZM43.152,43.151C51.669,34.633 51.666,20.82 43.144,12.298C34.623,3.777 20.809,3.773 12.292,12.291C3.774,20.809 3.778,34.622 12.299,43.144C20.821,51.666 34.634,51.669 43.152,43.151Z"
android:strokeAlpha="0.38964844"
android:strokeWidth="1"
android:fillColor="#354556"
android:fillType="nonZero"
android:strokeColor="#00000000"
android:fillAlpha="0.38964844"/>
</vector>
shape_rect_condition_bg_22.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="4dp"/>
<solid android:color="#E8EBEC"/>
</shape>