自定义View的编写
在项目的时候,很多情况要用到自定义View来达到自己想要的效果,所有自定义View的编写很重要。
首先看看所要实现的效果:
最上面的一行字“LogicView”每次从左向右滚动,下面的圆从角度0到360不断变化。并且颜色随机地变化。
MainActivity.java
1 package com.example.myview; 2 3 import android.os.Bundle; 4 import android.app.Activity; 5 import android.view.Menu; 6 7 public class MainActivity extends Activity { 8 9 @Override 10 protected void onCreate(Bundle savedInstanceState) { 11 super.onCreate(savedInstanceState); 12 setContentView(R.layout.activity_main); 13 //setContentView(new Myview(this)); 14 } 15 }
activity_main.xml
1 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 tools:context=".MainActivity" > 6 <com.example.myview.TestClass 7 android:layout_width="match_parent" 8 android:layout_height="match_parent" 9 10 /> 11 </FrameLayout>
TestClass.java
1 package com.example.myview; 2 3 import java.util.Random; 4 5 import android.content.Context; 6 import android.graphics.Canvas; 7 import android.graphics.Paint; 8 import android.graphics.RectF; 9 import android.util.AttributeSet; 10 import android.view.View; 11 12 public class TestClass extends View{ 13 14 private MyThread thread; 15 private Paint paint = new Paint(); 16 private float rx = 0; 17 private RectF rectF = new RectF(0,60,100,160); 18 private float sweepAngel = 0; 19 Random rand = new Random(); 20 21 public TestClass(Context context, AttributeSet attrs) { 22 super(context, attrs); 23 } 24 25 public TestClass(Context context) { 26 super(context); 27 } 28 29 private void drawSub(Canvas canvas){ 30 paint.setTextSize(30); 31 canvas.drawText("LogicView", rx, 30, paint); 32 33 canvas.drawArc(rectF,0,sweepAngel,true,paint); 34 } 35 36 protected void onDraw(Canvas canvas){ 37 if(thread==null){ 38 thread = new MyThread(); 39 thread.start(); 40 }else{ 41 drawSub(canvas); 42 } 43 } 44 45 private void logic(){ 46 rx++; 47 if(rx > getWidth()){ 48 rx = 0 - paint.measureText("LogicView"); 49 } 50 51 sweepAngel ++ ; 52 53 if(sweepAngel > 360){ 54 sweepAngel = 0; 55 } 56 int r = rand.nextInt(256); 57 int g = rand.nextInt(256); 58 int b = rand.nextInt(256); 59 paint.setARGB(255, r, g, b); 60 } 61 62 class MyThread extends Thread{ 63 @Override 64 public void run() { 65 while(true){ 66 logic(); 67 postInvalidate(); 68 try { 69 Thread.sleep(30); 70 } catch (InterruptedException e) { 71 e.printStackTrace(); 72 } 73 } 74 75 } 76 } 77 78 }