2.1.5 自定义view

来源:互联网 发布:mac os 终端命令 编辑:程序博客网 时间:2024/06/02 05:08

自定义view

public class Two_view extends View {    private float x = 50;    private float y = 50;    private Paint paint = null;    public Two_view(Context context, @Nullable AttributeSet attrs) {        super(context, attrs);        //创建画笔        paint = new Paint();        paint.setColor(0xff00ccff);    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        /*         *绘制一个小球         * 参数分别是 横纵左边 半径 画笔         */        canvas.drawCircle(x, y, 20, paint);    }    @Override    public boolean onTouchEvent(MotionEvent event) {        this.x = event.getX();        this.y = event.getY();        this.invalidate();        return true;    }}

布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:id="@+id/root"    android:layout_height="match_parent">    <com.example.android.two.tool.Two_view        android:layout_width="match_parent"        android:layout_height="match_parent"        android:background="#ffffff"/></LinearLayout>

代码

public class Two extends Activity {    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.two);    }}

页面

这里写图片描述

原创粉丝点击