为了实现一个跟随手指的小球,开发自定义的UI组件,这个UI组件将会在指定位置绘制一个小球,这个位置可以动态改变。当用户通过手指在屏幕上拖动时,程序监听手指动作
自定义类DrawView
public class DrawView extends View{
public float currentX=40;
public float currentY=50;
Paint paint=new Paint();
public DrawView(Context context) {
super(context);
}
public DrawView(Context context,AttributeSet attributeSet) {
super(context,attributeSet);
}
//绘制小球
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.BLACK);
canvas.drawCircle(currentX, currentY, 15, paint);
}
//小球的触碰事件
@Override
public boolean onTouchEvent(MotionEvent event) {
currentX = event.getX();
currentY = event.getY();
//通知当前组件重新绘制
invalidate();
return true;
}
}
activity_main.xml:
<LinearLayout
android:id="@+id/root"
android:layout_width="100dp"
android:layout_height="100dp"
android:orientation="horizontal" >
<com.example.util.DrawView
android:id="@+id/root"
android:layout_width="100dp"
android:layout_height="100dp" />
</LinearLayout>
MainActivity.class
public class MainActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout root=(LinearLayout)findViewById(R.id.root);
final DrawView drawView=new DrawView(MainActivity.this);
drawView.setMinimumHeight(100);
drawView.setMinimumWidth(100);
root.addView(drawView);
}
}