我尝试在屏幕上制作一个活动和一个视图,因为活动有我需要的按钮。我的问题是我怎么能这样做,当我启动应用程序时,我看到活动中的按钮和球和视图类中的框?
我应该如何看待布局中的视图?
即活动:
public class GameView extends Activity implements OnClickListener {
private Button bPAUSE;
private TextView tvTries;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameview);
initialize();
}
public void onClick(View v) {
}
public void initialize(){
bPAUSE = (Button) findViewById(R.id.button1);
bPAUSE.setOnClickListener(this);
tvTries = (TextView) findViewById(R.id.textView1);
}
}
View类:
public class BouncingBallView extends View {
private Ball ball;
private Box box;
// For touch inputs - previous touch (x, y)
private float previousX;
private float previousY;
// Constructor
public BouncingBallView(Context context) {
super(context);
box = new Box(0xff00003f); // ARGB
ball = new Ball(Color.GREEN);
// To enable keypad
this.setFocusable(true);
this.requestFocus();
// To enable touch mode
this.setFocusableInTouchMode(true);
}
// Called back to draw the view. Also called after invalidate().
@Override
protected void onDraw(Canvas canvas) {
// Draw the components
box.draw(canvas);
ball.draw(canvas);
// Update the position of the ball, including collision detection and reaction.
ball.moveWithCollisionDetection(box);
// Delay
try {
Thread.sleep(30);
} catch (InterruptedException e) { }
invalidate(); // Force a re-draw
}
// Called back when the view is first created or its size changes.
@Override
public void onSizeChanged(int w, int h, int oldW, int oldH) {
// Set the movement bounds for the ball
box.set(0, 0, w, h);
}
int touchCounter = 2;
@Override
public boolean onTouchEvent(MotionEvent event) {
float currentX = event.getX();
float currentY = event.getY();
float deltaX, deltaY;
float scalingFactor = 1.0f / ((box.xMax > box.yMax) ? box.yMax : box.xMax);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchCounter = 2;
if (currentX >= previousX) {
deltaX = currentX - previousX;
ball.speedX += deltaX * scalingFactor;
} else if (previousX >= currentX) {
deltaX = previousX - currentX;
ball.speedX += deltaX * scalingFactor;
} if (currentY >= previousY) {
deltaY = currentY - previousY;
ball.speedX += deltaY * scalingFactor;
} else if (previousY >= currentY) {
deltaY = previousY - currentY;
ball.speedY += deltaY * scalingFactor;
}
//vorherig(previous) - aktuell
break;
case MotionEvent.ACTION_UP:
touchCounter = 1;
// Modify rotational angles according to movement
break;
}
// Save current x, y
previousX = currentX;
previousY = currentY;
return true; // Event handled
}
}
我实际上是尝试在活动类中执行此操作,但缺少布局...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View BouncingBallView= new BouncingBallView(this);
setContentView(BouncingBallView);
initialize();
}