2018-11-14 Android 自定义TextView完成简单的进度条

自定义TextView 


public class MyProgressextends AppCompatTextView {

Paintpaint =new Paint();

    int x ;

    Rectrect;

    public MyProgress(Context context) {

super(context);

        initView();

    }

public MyProgress(Context context, @Nullable AttributeSet attrs) {

super(context, attrs);

        initView();

    }

public MyProgress(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {

super(context, attrs, defStyleAttr);

        initView();

    }

public void initView(){

rect =new Rect();

    }

@Override

    protected void onDraw(Canvas canvas) {

super.onDraw(canvas);

        paint.setColor(Color.GRAY);

        paint.setStyle(Paint.Style.FILL);

        rect.set(0,0,getMeasuredWidth(),getMeasuredHeight());

        canvas.drawRect(rect,paint);

        paint.setColor(Color.RED);

        if(x !=100){

canvas.drawRect(0,0,getMeasuredWidth()*x/100, getMeasuredHeight(),paint);

        }else{

paint.setColor(Color.GREEN);

            canvas.drawRect(0,0,getMeasuredWidth()*x/100, getMeasuredHeight(),paint);

        }

paint.setColor(Color.WHITE);

        paint.setTextSize(15);

        Paint.FontMetricsInt fontMetrics =paint.getFontMetricsInt();

        int baseline = (rect.bottom +rect.top - fontMetrics.bottom - fontMetrics.top) /2;

        paint.setTextAlign(Paint.Align.CENTER);

        canvas.drawText(x +"%",rect.centerX(),baseline,paint);

    }

public void setProgress(int x){

this.x = x;

        invalidate();

    }

}


调用的话,自己写个SeekBar测试即可:

MyProgress  myProgress = (MyProgress) findViewById(R.id.text);

seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

@Override

    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

           myProgress.setProgress(i);

    }

@Override

    public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override

    public void onStopTrackingTouch(SeekBar seekBar) {

}

});


布局文件

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical">

        android:id="@+id/seek_bar"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginTop="20dp"/>

        android:id="@+id/text"

        android:layout_width="200dp"

        android:layout_height="40dp"

        android:layout_marginTop="60dp"

        android:gravity="center"

        android:textColor="@android:color/holo_red_light"

        android:layout_gravity="center"/>

截图如下:

你可能感兴趣的:(2018-11-14 Android 自定义TextView完成简单的进度条)