十个小球运动,出不来效果?

沈墨?_? 发布于 2012/03/07 14:55
阅读 721
收藏 0
package com.bupt3g.ballsmove002;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.bupt3g.ballmove002.R;

public class BallsMove002Activity extends Activity {
 private RelativeLayout rl;
 private RelativeLayout.LayoutParams rllp2;
 private Timer tm;
 private TimerTask tk;
 private Balls ball;
 private Balls[] balls=new Balls[10]; 
 protected void onPause() {
  tm.cancel();
  tk.cancel();
  super.onPause();
 }
 protected void onResume() {
  tm=new Timer();
  tk=new TimerTask() {
   public void run() {
    hd.sendEmptyMessage(0);
   }
  };
  tm.schedule(tk, 10,10);
  super.onResume();
 }

 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  rl=(RelativeLayout) findViewById(R.id.rl);
  for (int i = 0; i < balls.length; i++) {
   ball=new Balls(this);
   balls[i]=ball;
   rl.addView(ball,30,30);
   rllp2=(LayoutParams) ball.getLayoutParams();
   rllp2.leftMargin=(int) (Math.random()*300);
   rllp2.topMargin=(int) (Math.random()*400);
  }
 }
 private Handler hd=new Handler(){
  public void handleMessage(android.os.Message msg) {
   ball.move();
   
  };
 };
}
另一个类
package com.bupt3g.ballsmove002;

import com.bupt3g.ballmove002.R;

import android.content.Context;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

public class Balls extends ImageView {
 private float sx=0;
 private float sy=0;
 private RelativeLayout.LayoutParams rllp;
 public Balls(Context context) {

  super(context);
  sx=(float)Math.random()*10;
  sy=(float)Math.random()*10;
  setImageResource(R.drawable.aaaa);
 }
 public void  move(){
  rllp=(LayoutParams) getLayoutParams();
  rllp.leftMargin+=sx;
  rllp.topMargin+=sy;
  if(rllp.leftMargin<0){
   sx=Math.abs(sx);
  }
  if(rllp.leftMargin>getParentWidth()-getWidth()){
   sx=-Math.abs(sx);
  }
  if(rllp.topMargin<0){
   sy=Math.abs(sy);
  }
  if(rllp.topMargin>getParentHeight()-getTop()){
   sy=-Math.abs(sy);
  }
  setLayoutParams(rllp);
 }
 private float getParentWidth(){
  return ((RelativeLayout)getParent()).getWidth();
 }
 private float getParentHeight(){
  return ((RelativeLayout)getParent()).getHeight();
 }
}
加载中
0
沈墨?_?
沈墨?_?

handler方法体改成

 public void handleMessage(android.os.Message msg) {
   for (Balls ball:balls) {
    ball.move();
   }

  };

0
沈墨?_?
沈墨?_?
我在别的地方找到个答案,不过有时候球会停,求高手指点。。
返回顶部
顶部