android surfaceview 雙執行緒實現計時的同時 可以隨意移動滑塊
阿新 • • 發佈:2019-02-05
不多說直接看程式。。改了一天終於改出來了。
(1)MyActivity 裡的程式碼
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//隱去標題欄
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//隱去狀態列
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new MySurfaceView(this));
}
}
(2)MySurfaceView裡的程式碼
(邏輯有點亂 慢慢看 改動太多 自己都醉了)
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import static android.graphics.Color.TRANSPARENT;
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder sfh;
private Paint paint;
private int textX=400,textY=400;
private int count = 0;
private MyTime myThread;
public MySurfaceView(Context context){
super(context);
sfh=this.getHolder();//例項SurfaceHolder
sfh.addCallback(this);//為SurfaceHolder新增狀態監聽
myThread = new MyTime(sfh);
}
public void surfaceCreated(SurfaceHolder holder){
myThread.isRun = true;
myThread.start();
myDraw();
}
public void surfaceChanged(SurfaceHolder holder,int fornat,int width,int height){
}
public void surfaceDestroyed(SurfaceHolder holder){
myThread.isRun = false;
}
public void myDraw(){
paint=new Paint();//例項一個畫筆
Canvas canvas =sfh.lockCanvas();
Bitmap bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.bar)).getBitmap();
canvas.drawColor(TRANSPARENT, PorterDuff.Mode.CLEAR);
canvas. drawBitmap(bitmap, textX, textY,paint);
paint.setColor(Color.GREEN);
paint.setTextSize(30);
canvas.drawText("這是第" + (count) + "秒", 100, 310, paint);
sfh.unlockCanvasAndPost(canvas);
}
public boolean onTouchEvent(MotionEvent event){
int x=(int)event.getX();
int y=(int)event.getY();
if(event.getAction()==MotionEvent.ACTION_DOWN){
textX=x-75;
textY=y-120;
} else if(event.getAction()==MotionEvent.ACTION_MOVE){
textX=x-75;
textY=y-120;
}else if(event.getAction()==MotionEvent.ACTION_UP){
textX=x-75;
textY=y-120;
}
myDraw();
return true;
}
class MyTime extends Thread
{
private SurfaceHolder holder;
public boolean isRun ;
public MyTime(SurfaceHolder holder)
{
this.holder =holder;
isRun = true;
}
@Override
public void run() {
// int count = 0;
while (isRun) {
Canvas c = null;
try {
count++;
Thread.sleep(1000);//睡眠時間為1秒
myDraw();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
}