自定義view(四)----自定義進(jìn)度view

本文主演參照前一篇文章打造了一個(gè)自定義的進(jìn)度條琳骡,僅作代碼記錄。
實(shí)現(xiàn)效果:


1645079823700.gif

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ProcessBarView">
        <attr name="innerColor" format="color"/>
        <attr name="outerColor" format="color"/>
        <attr name="borderWidth" format="dimension"/>
        <attr name="NumTextColor" format="color"/>
        <attr name="NumTextSize" format="dimension"/>
    </declare-styleable>
</resources>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    tools:context=".MainActivity">

    <com.example.view04.ProcessBarView
        app:NumTextSize="22sp"
        app:outerColor="#C0C0C0"
        android:id="@+id/processBarView"
        android:layout_width="200dp"
        android:layout_height="200dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:text="開(kāi)始"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="startAnimator"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/processBarView"
        tools:ignore="OnClick" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private ProcessBarView mProcessView;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mProcessView=findViewById(R.id.processBarView);

    }
    public void startAnimator(View view){
        mProcessView.setSweepAngle(0);
        ValueAnimator valueAnimator= ObjectAnimator.ofFloat(0,100);
        valueAnimator.setDuration(10000);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener(){

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float mSweepAngle= (float) animation.getAnimatedValue();
                //保留兩位小數(shù)
                BigDecimal b = new BigDecimal(mSweepAngle);
                double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                mProcessView.setSweepAngle((float) f1);
            }
        });
        valueAnimator.start();
    }
}

ProcessBarView.java

public class ProcessBarView extends View {
    private Context mContext;
    private int mOutColor;
    private int mInnerColor;
    private int mBorderWidth;
    private int mNumTextSize;
    private int mNumTextColor;
    private Paint mOutPaint;
    private Paint mInnerPaint;
    private Paint mTextPaint;



    private float mSweepAngle=0;
    private int mMaxAngle=100;

    public ProcessBarView(Context context) {
        this(context, null);
    }

    public ProcessBarView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ProcessBarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ProcessBarView);
        mOutColor = typedArray.getColor(R.styleable.ProcessBarView_outerColor, Color.RED);
        mInnerColor = typedArray.getColor(R.styleable.ProcessBarView_innerColor, Color.BLUE);
        mBorderWidth = (int) typedArray.getDimension(R.styleable.ProcessBarView_borderWidth, 20);
        mNumTextColor = typedArray.getColor(R.styleable.ProcessBarView_NumTextColor, Color.RED);
        mNumTextSize = typedArray.getDimensionPixelSize(R.styleable.ProcessBarView_NumTextSize, 20);

        mOutPaint=new Paint();
        mOutPaint.setAntiAlias(true);
        mOutPaint.setStrokeWidth(mBorderWidth);
        mOutPaint.setColor(mOutColor);
        mOutPaint.setStyle(Paint.Style.STROKE);
        mOutPaint.setStrokeCap(Paint.Cap.ROUND);

        mInnerPaint=new Paint();
        mInnerPaint.setAntiAlias(true);
        mInnerPaint.setStrokeWidth(mBorderWidth);
        mInnerPaint.setColor(mInnerColor);
        mInnerPaint.setStyle(Paint.Style.STROKE);
        mInnerPaint.setStrokeCap(Paint.Cap.ROUND);

        mTextPaint=new Paint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setColor(mNumTextColor);
        mTextPaint.setTextSize(mNumTextSize);

        typedArray.recycle();
    }

    public ProcessBarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        mContext=context;
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        setMeasuredDimension(widthSize > heightSize ? heightSize : widthSize, widthSize > heightSize ? heightSize : widthSize);
    }

    @Override
    public void draw(Canvas canvas) {
        //畫(huà)外圓
        super.draw(canvas);
        RectF rectf=new RectF(50,50,getWidth()-2*mBorderWidth,getHeight()-2*mBorderWidth);
        canvas.drawArc(rectf,0,360,false,mOutPaint);
        //畫(huà)內(nèi)圓
        canvas.drawArc(rectf,0,mSweepAngle/mMaxAngle*360,false,mInnerPaint);
        //畫(huà)文字
        String stepText = mSweepAngle+"%";
        Rect textBounds = new Rect();
        mTextPaint.getTextBounds(stepText, 0, stepText.length(), textBounds);//測(cè)量文字畫(huà)筆長(zhǎng)度
        int dx = getWidth() / 2 - textBounds.width() / 2;
        Paint.FontMetricsInt fontMetricsInt = mTextPaint.getFontMetricsInt();
        int dy = (fontMetricsInt.bottom - fontMetricsInt.top) / 2 - fontMetricsInt.bottom;
        int baseLine = getHeight() / 2 + dy;
        canvas.drawText(stepText, dx, baseLine, mTextPaint);
    }
    public void setSweepAngle(float sweepAngle){
        this.mSweepAngle=sweepAngle;
        invalidate();
    }
}

下面是兩個(gè)類的kotlin代碼實(shí)現(xiàn):
MainActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        start.setOnClickListener { startAnimator() }
    }

    private fun startAnimator() {
        processBarView!!.setSweepAngle(0.00)
        val valueAnimator = ObjectAnimator.ofFloat(0f, 100f)
        valueAnimator.duration = 10000
        valueAnimator.addUpdateListener { animation ->
            val mSweepAngle = animation.animatedValue
            //保留兩位小數(shù)
            val b: BigDecimal = BigDecimal(mSweepAngle.toString())
            val f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).toDouble()
            processBarView!!.setSweepAngle(f1)
        }
        valueAnimator.start()
    }
}

ProcessBarView

class ProcessBarView : View {
    private var mContext: Context? = null
    private var mOutColor = 0
    private var mInnerColor = 0
    private var mBorderWidth = 0
    private var mNumTextSize = 0
    private var mNumTextColor = 0
    private var mOutPaint: Paint? = null
    private var mInnerPaint: Paint? = null
    private var mTextPaint: Paint? = null
    private var mSweepAngle = 0.00
    private val mMaxAngle = 100

    @JvmOverloads
    constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ProcessBarView)
        mOutColor = typedArray.getColor(R.styleable.ProcessBarView_outerColor, Color.RED)
        mInnerColor = typedArray.getColor(R.styleable.ProcessBarView_innerColor, Color.BLUE)
        mBorderWidth = typedArray.getDimension(R.styleable.ProcessBarView_borderWidth, 20f).toInt()
        mNumTextColor = typedArray.getColor(R.styleable.ProcessBarView_NumTextColor, Color.RED)
        mNumTextSize = typedArray.getDimensionPixelSize(R.styleable.ProcessBarView_NumTextSize, 20)
        mOutPaint = Paint()
        mOutPaint!!.isAntiAlias = true
        mOutPaint!!.strokeWidth = mBorderWidth.toFloat()
        mOutPaint!!.color = mOutColor
        mOutPaint!!.style = Paint.Style.STROKE //該屬性代表非實(shí)心圓
        mOutPaint!!.strokeCap = Paint.Cap.ROUND

        mInnerPaint = Paint()
        mInnerPaint!!.isAntiAlias = true
        mInnerPaint!!.strokeWidth = mBorderWidth.toFloat()
        mInnerPaint!!.color = mInnerColor
        mInnerPaint!!.style = Paint.Style.STROKE
        mInnerPaint!!.strokeCap = Paint.Cap.ROUND

        mTextPaint = Paint()
        mTextPaint!!.isAntiAlias = true
        mTextPaint!!.color = mNumTextColor
        mTextPaint!!.textSize = mNumTextSize.toFloat()
        typedArray.recycle()
    }

    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes) {
        mContext = context
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)
        setMeasuredDimension(widthSize.coerceAtMost(heightSize), widthSize.coerceAtMost(heightSize))
    }

    override fun draw(canvas: Canvas) {
        //畫(huà)外圓
        super.draw(canvas)
        val rectf = RectF(
            50F,
            50F,
            (width - 2 * mBorderWidth).toFloat(),
            (height - 2 * mBorderWidth).toFloat()
        )
        canvas.drawArc(rectf, 0f, 360f, false, mOutPaint!!)
        //畫(huà)內(nèi)圓
        canvas.drawArc(rectf, 0f, (mSweepAngle / mMaxAngle * 360).toFloat(), false, mInnerPaint!!)
        //畫(huà)文字
        val stepText = "$mSweepAngle%"
        val textBounds = Rect()
        mTextPaint!!.getTextBounds(stepText, 0, stepText.length, textBounds) //測(cè)量文字畫(huà)筆長(zhǎng)度
        val dx = width / 2 - textBounds.width() / 2
        val fontMetricsInt = mTextPaint!!.fontMetricsInt
        val dy = (fontMetricsInt.bottom - fontMetricsInt.top) / 2 - fontMetricsInt.bottom
        val baseLine = height / 2 + dy
        canvas.drawText(stepText, dx.toFloat(), baseLine.toFloat(), mTextPaint!!)
    }

    fun setSweepAngle(sweepAngle: Double) {
        mSweepAngle = sweepAngle
        invalidate()
    }
}

使用kotlin代碼時(shí)怒坯,別忘了在app目錄下的build.gradle中添加插件

id 'kotlin-android-extensions'
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末炫狱,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子剔猿,更是在濱河造成了極大的恐慌视译,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,122評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件归敬,死亡現(xiàn)場(chǎng)離奇詭異酷含,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)汪茧,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)椅亚,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人陆爽,你說(shuō)我怎么就攤上這事什往。” “怎么了慌闭?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,491評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵别威,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我驴剔,道長(zhǎng)省古,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,636評(píng)論 1 293
  • 正文 為了忘掉前任丧失,我火速辦了婚禮豺妓,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己琳拭,他們只是感情好训堆,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,676評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著白嘁,像睡著了一般坑鱼。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上絮缅,一...
    開(kāi)封第一講書(shū)人閱讀 51,541評(píng)論 1 305
  • 那天鲁沥,我揣著相機(jī)與錄音,去河邊找鬼耕魄。 笑死画恰,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的吸奴。 我是一名探鬼主播允扇,決...
    沈念sama閱讀 40,292評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼奄抽!你這毒婦竟也來(lái)了蔼两?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,211評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤逞度,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后妙啃,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體档泽,經(jīng)...
    沈念sama閱讀 45,655評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,846評(píng)論 3 336
  • 正文 我和宋清朗相戀三年揖赴,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了馆匿。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,965評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡燥滑,死狀恐怖渐北,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情铭拧,我是刑警寧澤赃蛛,帶...
    沈念sama閱讀 35,684評(píng)論 5 347
  • 正文 年R本政府宣布,位于F島的核電站搀菩,受9級(jí)特大地震影響呕臂,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜肪跋,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,295評(píng)論 3 329
  • 文/蒙蒙 一歧蒋、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦谜洽、人聲如沸萝映。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,894評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)序臂。三九已至,卻和暖如春敌呈,著一層夾襖步出監(jiān)牢的瞬間贸宏,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,012評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工磕洪, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留吭练,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,126評(píng)論 3 370
  • 正文 我出身青樓析显,卻偏偏與公主長(zhǎng)得像鲫咽,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子谷异,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,914評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容