1. 程式人生 > >Android自定義View畫圓+進度條+自定義View梯形

Android自定義View畫圓+進度條+自定義View梯形

//自定義進度圓圈
package com.bw.20171104;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by user on 2017/11/4.
*/ public class ViewBar extends View { Paint paint;//畫筆 private int mProgress=0;//進度條的進度 private int mCountProgress=0;//圓環中間的文字表示進度條的進度百分比 private float mRadiuSize = 0;//外圓的半徑 private float mRingSize = 0;//弧的寬度 private float mTextSize = 0;//圓環中間的文字大小 private int mProgressColor = 0;//表示進度條的顏色 public static final int
STROKE = 0; public static final int FILL = 1; public ViewBar(Context context) { this(context, null); init(); } public ViewBar(Context context, AttributeSet attrs) { super(context, attrs); getCustomAttr(context,attrs);//attrs為控制元件中的屬性集合 init(); } public
ViewBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void getCustomAttr(Context context, AttributeSet attrs) { TypedArray array=context.obtainStyledAttributes(attrs,R.styleable.ViewBar); //第一個引數為控制元件中輸入的值,第二個引數為預設值 mRadiuSize=array.getDimension(R.styleable.ViewBar_radiuSize,100); mRingSize=array.getDimension(R.styleable.ViewBar_ringSize,10); mTextSize=array.getDimension(R.styleable.ViewBar_textSize,10); mProgressColor=array.getColor(R.styleable.ViewBar_progressColor,Color.BLACK); } private void init() { paint=new Paint();//建立畫筆物件 paint.setAntiAlias(true);//抗鋸齒 } //warpcontent型別 MeasureSpec.AT_MOST //matchparent型別 或者具體的長度 100dp 200dp MeasureSpec.EXACTLY @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthMode=MeasureSpec.getMode(widthMeasureSpec);//獲取寬的模式 int heightMode=MeasureSpec.getMode(heightMeasureSpec);//獲取高的模式 int widthSize=MeasureSpec.getSize(widthMeasureSpec);//獲取輸入的寬的值 int heightSize=MeasureSpec.getSize(heightMeasureSpec);//獲取輸入的高的值 int width=0; int height=0; if (widthMode==MeasureSpec.AT_MOST){ width=(int)(mRadiuSize*2); }else { width=Math.max(widthSize,(int)(mRadiuSize*2)); } if (heightMode==MeasureSpec.AT_MOST){ height=(int)(mRadiuSize*2); }else { height=Math.max(heightSize,(int)(mRadiuSize*2)); } //給自定義控制元件設定寬高 setMeasuredDimension(width,height); }
    @Override
protected void onDraw(Canvas canvas) {
	//設定畫筆,螢幕大小
        paint.setStrokeWidth(0);
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.STROKE);
        int ring=getMeasuredWidth()/2;
        canvas.drawCircle(ring,ring,mRadiuSize,paint);
        canvas.drawCircle(ring,ring,mRadiuSize-mRingSize,paint);

        paint.setTextSize(mTextSize);
        String text=mCountProgress+"%";
        float textWidth=paint.measureText(text);
        canvas.drawText(text,ring-textWidth/2,ring+textWidth/2,paint);
        RectF rectF=new RectF(ring-mRadiuSize+mRingSize/2,ring-mRadiuSize+mRingSize/2,ring+mRadiuSize-mRingSize/2,ring+mRadiuSize-mRingSize/2);
        paint.setStrokeWidth(mRingSize);
        paint.setColor(mProgressColor);
        canvas.drawArc(rectF,0,mProgress,false,paint);

    }
    public void setProgress(int progress){
        mProgress=progress;
        mCountProgress=progress*100/360;
        invalidate();
    }
}
//Main進行非同步處理,點選監聽,跳轉
package com.bw.20171104;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView mBut;
    private Button mBut1;
    private ViewBar progress;

    @Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

    }

    private void initView() {
        mBut = (ImageView) findViewById(R.id.but);
        mBut.setOnClickListener(this);
        mBut1 = (Button) findViewById(R.id.but1);
        mBut1.setOnClickListener(this);
        progress = (ViewBar) findViewById(R.id.progress);
    }

    @Override
public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.but:
                Intent intent = new Intent(MainActivity.this, UserActivity.class);
                startActivity(intent);
                break;
            case R.id.but1:
                new AsyncTask<String, Integer, String>() {
                    @Override
protected String doInBackground(String... strings) {
                        for (int i = 0; i <= 360; i++) {
                            SystemClock.sleep(100);
                            publishProgress(i);
                        }
                        return null;
                    }

                    @Override
protected void onProgressUpdate(Integer... values) {
                        super.onProgressUpdate(values);
                        progress.setProgress(values[0]);

                    }

                    @Override
protected void onPostExecute(String s) {
                        super.onPostExecute(s);
                        //掃描二維碼
Intent intent1 = new Intent(MainActivity.this, MipcaActivityCapture.class);
                        intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent1);
                    }
                }.execute();
                break;

        }
    }
}
//自定義梯形View
package com.bw.20171104;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by user on 2017/11/4.
 * 自定義View
 */
public class MyView extends ViewGroup {
    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        MarginLayoutParams params = null;
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        measureChildren(widthMeasureSpec,heightMeasureSpec);

        //開始處理wrap_content,如果一個子元素都沒有,就設定為0
if (getChildCount() == 0) {
            setMeasuredDimension(0,0);
        } else if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
            //ViewGroup,寬,高都是wrap_content,根據我們的需求,寬度是子控制元件的寬度,高度則是所有子控制元件的總和
View childOne = getChildAt(0);
            params = (MarginLayoutParams) childOne.getLayoutParams();
            int childWidth = childOne.getMeasuredWidth();
            int childHeight = childOne.getMeasuredHeight();
            setMeasuredDimension(childWidth + params.leftMargin + params.rightMargin,
                    childHeight * getChildCount() + params.topMargin + params.bottomMargin);

        } else if (widthMode == MeasureSpec.AT_MOST) {
            //ViewGroup的寬度為wrap_content,則高度不需要管,寬度還是自控制元件的寬度
View childOne = getChildAt(0);
            params = (MarginLayoutParams) childOne.getLayoutParams();
            int childWidth = childOne.getMeasuredWidth();
            setMeasuredDimension(childWidth + params.leftMargin + params.rightMargin,heightSize);
        } else if (heightMode == MeasureSpec.AT_MOST) {
            //ViewGroup的高度為wrap_content,則寬度不需要管,高度為子View的高度和
View childOne = getChildAt(0);
            params = (MarginLayoutParams) childOne.getLayoutParams();
            int childHeight = childOne.getMeasuredHeight();
            setMeasuredDimension(widthSize, childHeight * getChildCount() + params.topMargin + params.bottomMargin);
        }
    }

    @Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(),attrs);
    }

    @Override
protected LayoutParams generateDefaultLayoutParams() {
        return new MarginLayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
    }

    @Override
protected LayoutParams generateLayoutParams(LayoutParams p) {
        return new MarginLayoutParams(p);
    }
    @Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int row = 0;
        int right = 0;
        int bottom = 0;
        for (int i = 0; i < getChildCount(); i++) {
            View childView = getChildAt(i);
            int childW = childView.getMeasuredWidth();
            int childH = childView.getMeasuredHeight();
            right += childW;
            bottom += row * (childH+5)+childH;
            if (right>r){
                row++;
                right = childW;
                bottom += row * (childH+5)+childH;
            }
            childView.layout(right - childW,bottom - childH,right,bottom);
        }
    }
}
//佈局檔案
//MainActivity--xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.bw.2017.MainActivity">

    <include layout="@layout/title"></include>

    <RelativeLayout
android:layout_width="match_parent"
android:layout_height="300dp">
        <com.bw.qiaoxiaohui20171104.ViewBar
android:id="@+id/progress"
android:layout_width="150dip"
android:layout_height="150dip"
android:layout_centerInParent="true"
app:ringSize="10dp"
app:progressColor="#afa"
app:radiuSize="100dp"
app:textSize="20dp" />
    </RelativeLayout>


    <Button
android:id="@+id/but1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginRight="100dp"
android:background="#619F86"
android:text="掃描二維碼"
android:textColor="#8D5F65" />
</LinearLayout>
//res/valuse/attrs
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ViewBar">
        <!--format表示型別-->
        <!--progressColor表示進度條的顏色-->
<attr name="progressColor" format="color" />
        <!--textSize圓環中間的文字大小-->
<attr name="textSize" format="dimension" />
        <!--ringSize弧的寬度-->
<attr name="ringSize" format="dimension" />
        <!--radiuSize外圓的半徑-->
<attr name="radiuSize" format="dimension" />
    </declare-styleable>
</resources>
//自定義梯形View佈局檔案
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.bw.20171104.UserActivity">

    <include layout="@layout/title"></include>

    <com.bw.20171104.MyView
android:layout_width="match_parent"
android:layout_height="match_parent">

        <TextView
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="#619EA0" />

        <TextView
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="#7561A0" />

        <TextView
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="#9FA061" />
    </com.bw.20171104.MyView>
</LinearLayout>