这次的学习主要是在包里面除自动生成的mainactivity.java之外,再新建一个class, DrawView,在mainactivity里面调用DrawView。
在DrawView里面主要是重写onDraw方法,----该方法负责在该组件指定位置绘制一个小球。
package org.crazyit.helloworld; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.View; public class DrawView extends View{ public float currentX=40; public float currentY=50; //必须重写一个构造方法 public DrawView(Context context) { super(context); // TODO Auto-generated constructor stub } //重写onDraw方法通过Canvas绘画 @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); //创建画笔 Paint paint=new Paint(); paint.setColor(Color.RED); //绘制一个小圆 canvas.drawCircle(currentX, currentY, 25, paint); } }
在mainactivity里面引用drawview.
package org.crazyit.helloworld; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.LinearLayout; public class MainActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout root=(LinearLayout) findViewById(R.id.root); //创建一个自己继承于View的对象 final DrawView drawView=new DrawView(this); //设置自定义组件的最大宽度和高度 drawView.setMinimumWidth(300); drawView.setMinimumHeight(500); //为drawview组件绑定tounch事件 drawView.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { Log.e("onTouch", "onTouch"); drawView.currentX=event.getX(); drawView.currentY=event.getY(); //通知drawview组件重绘 drawView.invalidate(); //返回true表明算是方法已经处理该事件 return true; } }); root.addView(drawView); } }
main.xml中为:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="#00FFCC" //定义背景颜色 android:id="@+id/root"> </LinearLayout>
最终结果:
时间: 2024-11-10 08:59:01