自定义View

package com.zcp.app;

import java.util.Timer;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

public class ImgView extends View{

private Paint paint;
private float curretX=0;
private float curretY=150;

public ImgView(Context context) {
super(context);
}
public ImgView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ImgView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
Timer timer=new Timer();
@Override
protected void onDraw(Canvas canvas) {
paint=new Paint();
paint.setColor(Color.RED);
// paint.setStrokeWidth(10f);
// canvas.drawColor(Color.BLUE);
// canvas.drawLine(50,50,200,50, paint);
canvas.drawCircle(curretX,curretY,15, paint);
super.onDraw(canvas);
handler.sendEmptyMessageDelayed(1, 50);
}

Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
WindowManager ger=((Activity) getContext()).getWindowManager();
int i=ger.getDefaultDisplay().getWidth();
if(curretX<i){
curretX+=3;
}else if(curretX>=i){
curretX=0;
}
invalidate();

};

};

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// setMeasuredDimension(200,200);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

// @Override
// public boolean onTouchEvent(MotionEvent event) {
// //当前组件的curretX、curretY两个属性
// this.curretX=event.getX();
// this.curretY=event.getY();
// //通知该组件重绘
// this.invalidate();
//
// return true;
//
// }
}

 

// Activity

package com.zcp.view;

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);
}

}

 

<RelativeLayout 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.zcp.app.ImgView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerHorizontal="true"

        android:layout_centerVertical="true"

        />

 

</RelativeLayout>

posted @ 2016-05-05 08:25  夏夜微凉  阅读(123)  评论(0编辑  收藏  举报