在项目的时候,很多情况要用到自定义View来达到自己想要的效果,所有自定义View的编写很重要。
首先看看所要实现的效果:
最上面的一行字“LogicView”每次从左向右滚动,下面的圆从角度0到360不断变化。并且颜色随机地变化。
MainActivity.java
package com.example.myview; import android.os.Bundle;
import android.app.Activity;
import android.view.Menu; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(new Myview(this));
}
}
activity_main.xml
<FrameLayout 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"
tools:context=".MainActivity" >
<com.example.myview.TestClass
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
TestClass.java
package com.example.myview; import java.util.Random; import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View; public class TestClass extends View{ private MyThread thread;
private Paint paint = new Paint();
private float rx = ;
private RectF rectF = new RectF(,,,);
private float sweepAngel = ;
Random rand = new Random(); public TestClass(Context context, AttributeSet attrs) {
super(context, attrs);
} public TestClass(Context context) {
super(context);
} private void drawSub(Canvas canvas){
paint.setTextSize();
canvas.drawText("LogicView", rx, , paint); canvas.drawArc(rectF,,sweepAngel,true,paint);
} protected void onDraw(Canvas canvas){
if(thread==null){
thread = new MyThread();
thread.start();
}else{
drawSub(canvas);
}
} private void logic(){
rx++;
if(rx > getWidth()){
rx = - paint.measureText("LogicView");
} sweepAngel ++ ; if(sweepAngel > ){
sweepAngel = ;
}
int r = rand.nextInt();
int g = rand.nextInt();
int b = rand.nextInt();
paint.setARGB(, r, g, b);
} class MyThread extends Thread{
@Override
public void run() {
while(true){
logic();
postInvalidate();
try {
Thread.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
} }