简单的自定义View下,参考李刚疯狂Andriod
package com.utils.MyDemo; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; public class MyView extends View { public float currentX=40; public float currentY=40; public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub } public MyView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint=new Paint(); paint.setColor(Color.GREEN); canvas.drawCircle(currentX, currentX, 15, paint); } }主要需要重新父类构造方法,几个方法切记不要删除。
在XML引用如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <com.utils.MyDemo.MyView android:id="@+id/myView" android:layout_height="wrap_content" android:layout_width="wrap_content" /> </LinearLayout>
在Activity中修改
public class MainActivity extends Activity { /** Called when the activity is first created. */ private MyView myView=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myView=(MyView)this.findViewById(R.id.myView); myView.setMinimumHeight(500); myView.setMinimumWidth(300); myView.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View arg0, MotionEvent event) { myView.currentX=event.getX(); myView.currentY=event.getY(); myView.invalidate(); return true; } }); } }
原文地址:http://blog.csdn.net/nothingl3/article/details/44493913