我正在尝试创建一个 Android 应用程序,用户可以在其中将任何圆圈拖到另一个圆圈上,并且文本框应该显示这两个圆圈的总和。每次程序启动时,它应该显示具有随机位置和随机数从 1 -9 的圆圈。
不幸的是,我已经创建了一个圆圈,但当我尝试拖动它时,应用程序崩溃了。还请帮助我使用该应用程序的其余功能。谢谢。
最终输出应如下所示:
MainActivity.java
package com.dragandadd;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FrameLayout main = (FrameLayout) findViewById(R.id.activity_main);
main.addView(new Ball(this,50,50,25));
main.addView(new Ball(this,50,50,25));
main.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent e) {
float x = e.getX();
float y = e.getY();
FrameLayout flView = (FrameLayout) v;
flView.addView(new Ball(getParent(), x,y,25));
return true;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Ball.java
package com.dragandadd;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
public class Ball extends View {
final float x;
final float y;
final int r;
final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public Ball(Context context, float x, float y, int r) {
super(context);
mPaint.setColor(0xFFFF0000);
this.x = x;
this.y = y;
this.r = r;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, r, mPaint);
}
}
活动主
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FF66FF33" />