2015-02-03 4 views
0

이미지 뷰 (공)가 레이아웃을 돌아 다니고 buttom을 눌렀을 때 멈추기 전에 여러 번 튀어 나오려고한다. 비록 로그캣이 일어난다 고 말하지만, 움직이지는 않는다.이미지 뷰가 움직이지 않는다

는 여기가

public class BallPhisics { 
int x =400; 
int y = 0; 
boolean bounceX = false; 
boolean bounceY= false; 
int counter =0; 
ImageView object; 
public BallPhisics(ImageView i){ 
    object=i; 
} 

public void applyMovement() { 
    while (true) { 
     object.setLeft((int) object.getX()+x); //i know i shouldnt use pixels 
     Log.d("EVENT", "X moved");  Log.d("Ended",Integer.toString(object.getLeft())); 

     object.setBottom((int)(object.getY() + y)); 
     Log.d("EVENT", "Y moved"); 
     try { 
      Thread.sleep(1000); 
      Log.d("EVENT", "Time 1 used"); 
     } catch(InterruptedException ex) { 
      Thread.currentThread().interrupt(); 
     } 

     if (object.getX()<=50||(object.getRight()<=50)){ 
      bounceX =true; 
      break; 
     } 
     if (object.getY()<=50||object.getTop()<=50){ 
      bounceY=true; 
      break; 
     } 
    } 
    this.bouncing(); 

} 
public void bouncing(){ 
    Log.d("EVENT", "Bouncing!!"); 
    if (bounceX&&bounceY){ 
     x=-x; 
     y=-y; 
    } 
    else if (bounceX){ 
     x=-x; 
     y=(int)(Math.random()*100- 50 +y); 
    } 
    else if (bounceY) { 
     x = (int) (Math.random() * 100 - 50 + x); 
     y = -y; 
    } 
    counter++; 
    if(counter==5){return;} 
    this.applyMovement(); 
} 

그리고 mainActivity에 onclick 이벤트

입니다.

public void StartBall (View view){ 
    ImageView imageview=(ImageView) findViewById(R.id.imageView); 
    BallPhisics phisics = new BallPhisics(imageview); 
    Log.d("EVENT", Integer.toString(imageview.getLeft())+" before"); 
    phisics.applyMovement(); 
    Log.d("EVENT",Integer.toString(imageview.getLeft())+" after"); 

} 

죄송합니다. 그런데 누군가는보기를 움직이는 적절한 방법을 알고 있습니까? 사전에

감사 아마 setLeft (int left), 또는이 메소드가 레이아웃 시스템에 의해 호출하기위한 것입니다 일반적으로 다른 호출 할 수 없습니다 때문에 setBottom (int bottom), according to the documentation을 사용하는 것이 좋습니다 아니에요보기를 이동하는 모든

+0

while (true) 및 ui 스레드의 Thread.sleep은 나쁜 생각이 있습니다. – Blackbelt

+0

예,하지만 이것은 단지 실험입니다. –

+0

왜 제발? 확실하지 않습니다. logcat은 아무렇지도 않은 것 같습니다 –

답변

0

우선 .

동적으로보기를 이동하려면 허니컴 (API 레벨 11)으로 지원을 제한 할 수있는 경우 LayoutParams 또는 setX (float x)setY (float Y)을 살펴 봐야합니다.

어느 것을 사용하든 부드러운 움직임을 얻기가 어려울 수 있습니다. 따라서 뷰 애니메이션 시스템을 사용하여 ImageView의 트위닝 된 애니메이션을 수행하는 것이 좋습니다.

다음은 왼쪽에서 오른쪽으로 시작하여 임의의 y 좌표로 ImageView를 움직이는 체인 애니메이션의 예입니다. 하나의 x- 경계에서 다음 x- 경계로의 각 변환 후에, onAnimationEnd이 호출되어 다른 방향으로 애니메이션을 시작합니다.

public class MainActivity extends Activity { 

    //the ImageView you want to animate 
    private ImageView imageview; 

    private Animation mAnimation; 

    //The coordinates the view moved to in the last animation 
    private float lastX=0; 
    private float lastY=0; 
    private float secondlastY; 

    //Listener that implements a translate animation chain 
    AnimationListener animationListener=new AnimationListener() { 
     @Override 
     public void onAnimationEnd(Animation animation) { 

      float newY=(float)(Math.random()*0.75); 

      //this prevents that we move back to the position we came from 
      // to get a more natural bounce animation 
      while(newY<=secondlastY+0.15 && newY>=secondlastY-0.15){ 
       newY=(float)(Math.random()*0.75); 
      } 

      if(lastX==0.75f){ 
       //test if we are on the right border of the parent 
       mAnimation=newAnimation(lastX,lastY,0f,newY); 
       mAnimation.setAnimationListener(animationListener); 
       lastX=0f; 

      }else if(lastX==0.0f){ 
       //test if we are on the left border of the parent 
       mAnimation=newAnimation(lastX,lastY,0.75f,newY); 
       mAnimation.setAnimationListener(animationListener); 
       lastX=0.75f; 
      } 

      secondlastY=lastY; 
      lastY=newY; 
      imageview.startAnimation(mAnimation); 
     } 
    }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    imageview=(ImageView) findViewById(R.id.imageView); 

    //the coordinates the first animation should move to 
    lastY=(float)(Math.random()*0.75); 
    lastX=0.75f; 

    mAnimation=newAnimation(0f,0f,lastX,lastY); 
    mAnimation.setAnimationListener(animationListener); 
    imageview.startAnimation(mAnimation); 
} 

    //Method that returns a new animation with given start and end coordinates 
    private Animation newAnimation(float startX, float startY, float endX, float endY){ 
    Animation mAnimation = new TranslateAnimation(
       TranslateAnimation.RELATIVE_TO_PARENT, startX, 
       TranslateAnimation.RELATIVE_TO_PARENT, endX, 
       TranslateAnimation.RELATIVE_TO_PARENT, startY, 
       TranslateAnimation.RELATIVE_TO_PARENT, endY); 
    mAnimation.setDuration(2500); 
    mAnimation.setRepeatCount(0); 
    mAnimation.setRepeatMode(Animation.REVERSE); 
    mAnimation.setFillAfter(true); 

    return mAnimation; 
} 

}

참고 : 부모가 폭과 높이에 번역 애니메이션은 상대적입니다. 보기를 x = 1.0 또는 y = 1.0으로 완전히 이동하면보기의 일부가 부모 레이아웃 밖으로 이동합니다. 이 예제에서는 충분하기 때문에 어느 방향 으로든 최대 위치에 0.75를 설정하기로했습니다. 하지만 ImageView와 ParentLayout의 너비와 높이를 동적으로 설정해야합니다.

+0

좋아요! 그건 그렇고, 가속 많은 TranslateAnimation 또는 특정 메서드 또는 클래스가 무엇입니까? –

+0

Interpolator 클래스는 [link] (http://developer.android.com/reference/android/view/animation/package-summary.html)에서 찾을 수 있습니다. 예를 들어 변경 속도를 천천히 시작한 다음 가속화 할 수 있습니다. newAnimation 함수에 다음과 같이 간단하게 추가하면됩니다 :'mAnimation.setInterpolator (new AccelerateInterpolator());'. 전체적으로 동작 속도를 높이려면 애니메이션 기간을 줄입니다. – Rofti

관련 문제