配置DrawView类用于绘制小球
代码语言:javascript复制public class DrawView extends View {
public float currentX = 40;
public float currentY = 50;
//定义并创建画笔
Paint p = new Paint();
public DrawView(Context context)
{
super(context);
}
public DrawView(Context context , AttributeSet set)
{
super(context,set);
}
@Override
public void onDrawForeground(Canvas canvas) {
super.onDrawForeground(canvas);
//设置画笔颜色
p.setColor(Color.RED);
//绘制一个小球
canvas.drawCircle(currentX , currentY , 30 , p);
}
//为组建的触碰实践重写处理方法
@Override
public boolean onTouchEvent(MotionEvent event) {
//修改currentX,currentY的两个属性
currentX = event.getX();
currentY = event.getY();
//通知当前组建重绘自己
invalidate();
//放回true表明该处理方法已经处理该事件
return true;
}
}
MainActivity
代码语言:javascript复制public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取Linearlayout布局容器
LinearLayout root = (LinearLayout) findViewById(R.id.root);
//创建DrawView组件
final DrawView draw = new DrawView(this);
//设定自定义组件的最小宽度、高度
draw.setMinimumWidth(300);
draw.setMinimumHeight(500);
root.addView(draw);
}
}
xml文件
代码语言:javascript复制<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@ id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.a30797.myapplication.DrawView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
**注:**由上面布局,已经添加了自定义组件,因此Activity代码可简化为:
代码语言:javascript复制public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
示例: