本文实例讲述了Android开发实现跟随手指的小球效果。分享给大家供大家参考,具体如下:
配置DrawView类用于绘制小球
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
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文件
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">
android:layout_width="match_parent"
android:layout_height="match_parent" />
**注:**由上面布局,已经添加了自定义组件,因此Activity代码可简化为:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
示例:
希望本文所述对大家Android程序设计有所帮助。