Android 自訂View

來源:互聯網
上載者:User

標籤:.net   android   near   androi   鋸齒   and   ogre   utf-8   err   

Android提供的控制項有時候無法滿足我們項目的需求,所以需要我們自訂View的樣式以及事件監聽。

自訂View的步驟:

1、自訂View的屬性

2、在View的構造方法中獲得我們自訂的屬性

3、重寫onMesure

4、重寫onDraw

其中3不一定是必須的,當然了大部分情況下還是需要重寫的。

下面通過實現一個圓來展示進度進行分析。

1> 自訂View的屬性,首先在res/values/  下建立一個attrs.xml 。

<?xml version="1.0" encoding="utf-8"?><resources>    <attr name="firstcolor" format="color"/>    <attr name="secondcolor" format="color"/>    <attr name="speed" format="integer"/>    <attr name="circlewidth" format="dimension"/>    <declare-styleable name="CircleView">        <attr name="firstcolor"/>        <attr name="secondcolor"/>        <attr name="speed"/>        <attr name="circlewidth"/>     </declare-styleable></resources>

2> 在布局中聲明自訂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"    xmlns:custom="http://schemas.android.com/apk/res-auto"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.example.selfview.MainActivity">    <com.example.selfview.CircleView        android:layout_gravity="center"        android:layout_width="200dp"        android:layout_height="200dp"        custom:firstcolor="#FFF0"        custom:secondcolor="#000"        custom:circlewidth="20sp"        custom:speed="10"        /></LinearLayout>

3> 在自訂view的方法中,擷取我們的樣式以及畫圖。重寫了3個構造方法,預設的布局檔案調用的是兩個參數的構造方法。

public class CircleView extends View {    private int firstcolor;    private int secondcolor;    private int speed;    private int criclewidth;    private Paint mPaint;    private int mProgress;    public CircleView(Context context) {        this(context,null);    }    public CircleView(Context context, AttributeSet attrs) {        this(context, attrs,0);    }    public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CircleView, defStyleAttr, 0);        firstcolor = a.getColor(R.styleable.CircleView_firstcolor, Color.GREEN);        secondcolor = a.getColor(R.styleable.CircleView_secondcolor,Color.RED);        criclewidth = a.getDimensionPixelSize(R.styleable.CircleView_circlewidth, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX,20,getResources().getDisplayMetrics()));        speed = a.getInt(R.styleable.CircleView_speed,20);        a.recycle();        new Thread(new Runnable() {            @Override            public void run() {                while (true){                    try {                        Thread.sleep(100);                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                    if (mProgress <= 360){                        mProgress += speed;                    }else {                        Thread.interrupted();                    }                }            }        }).start();    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        int centre = getWidth() / 2;        int radius = centre - criclewidth / 2;        mPaint = new Paint();        mPaint.setStrokeWidth(criclewidth); // 設定圓環的寬度        mPaint.setAntiAlias(true); // 消除鋸齒        mPaint.setStyle(Paint.Style.STROKE); // 設定空心        RectF oval = new RectF(centre - radius, centre - radius, centre + radius, centre + radius);        mPaint.setColor(firstcolor); // 設定圓環的顏色        canvas.drawCircle(centre, centre, radius, mPaint); // 畫出圓環        mPaint.setColor(secondcolor); // 設定圓環的顏色        canvas.drawArc(oval, -90, mProgress, false, mPaint); // 根據進度畫圓弧        Log.d("azheng",String.valueOf(mProgress));        invalidate();    }}

4> 因為我們是靜態自訂view,所以在MainActivity中不需要調用。

public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }}

到這裡,我們的執行個體就可以運行了。

我們沒有重寫onMeasure方法,必要的情況下,可以通過該方法來調整我們的view的顯示。當然,我們也可以為自訂的view設定事件監聽,比如在構造方法中通過

this.setOnClickListener()實現點擊監聽。

參考:

    http://blog.csdn.net/lmj623565791/article/details/24252901/

Android 自訂View

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.