2016-12-21 28 views
0

我有一個用於我的佈局背景的圖像。我希望它開始向右移動,而從右側消失的每一幀都應該重新出現在左側。因此,只有一張照片,圖像會持續移動。我怎樣才能做到這一點?連續移動背景到右側並使其從左側重新出現

+1

嘗試,如果是這樣的你想要[如何在Android中從左向右移動圖像](http://stackoverflow.com/questions/4689918/how-to-move-an-image-from-left-to-right-in-android ) – BrunoM24

回答

0

這樣做的最簡單和最快的方式,它是在一個ViewGroup有兩個ImageView S和兩個型動物動畫動畫。通過獲取容器的寬度,第一個將從其位置(START)移動到右邊緣(PARENT_WIDTH),第二個將從容器外部(-PARENT_WIDTH)移動到內部(START)。最後,使動畫重複INFINITE將做一個真正的循環的幻覺。

private ViewGroup parent; 
private ImageView imgInner, imgOutter; 

@Override 
public void onCreate(...) { 
    ... 
    parent = (ViewGroup) findViewById(R.id.parent_loop); 
    imgInner = (ImageView) findViewById(R.id.image_loop_inner); 
    imgOutter = (ImageView) findViewById(R.id.image_loop_outter); 
    ... 
    setImageLoop(); 
} 

private void setImageLoop() { 
    // Need a thread to get the real size or the parent 
    // container, after the UI is displayed 
    imgInner.post(new Runnable() { 
     @Override 
     public void run() { 
      TranslateAnimation outAnim = 
        new TranslateAnimation(
          0f, parent.getWidth(), 0f, 0f); 
        // move from 0 (START) to width (PARENT_SIZE) 
      outAnim.setInterpolator(new LinearInterpolator()); 
      outAnim.setRepeatMode(Animation.INFINITE); // repeat the animation 
      outAnim.setRepeatCount(Animation.INFINITE); 
      outAnim.setDuration(2000); 

      TranslateAnimation inAnim = 
        new TranslateAnimation(
          - parent.getWidth(), 0f, 0f, 0f); 
        // move from out width (-PARENT_SIZE) to 0 (START) 
      inAnim.setInterpolator(new LinearInterpolator()); 
      inAnim.setRepeatMode(Animation.INFINITE); 
      inAnim.setRepeatCount(Animation.INFINITE); 
      inAnim.setDuration(2000); // same duration as the first 

      imgInner.startAnimation(outAnim); // start first anim 
      imgOutter.startAnimation(inAnim); // start second anim 
     } 
    }); 
} 

容器的ViewGroup在其寬度match_parent,但它可以被改變,並且因此START屬性將通過類似parent.getLeft()來代替。這種佈局可能是LinearLayoutRelativeLayout或其他。例如,我用這個:

<FrameLayout 
    android:layout_width="match_parent" 
    android:layout_height="250dp" 
    ...> 

    <ImageView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     .../> 

    <ImageView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     .../> 
</FrameLayout> 

這給了我這個輸出(牢記GIF使它看起來波濤洶涌當它是真的不):

Infinite loop for imageviews from right to left

+0

非常感謝。工作! –

0

更新代碼:

img = (ImageView) findViewById(R.id.imageView1); 
TranslateAnimation animation = new TranslateAnimation(-95.0f, 740.0f, 
      0.0f, 0.0f); // new TranslateAnimation(xFrom,xTo, yFrom,yTo) 
animation.setDuration(5000); // animation duration 
animation.setRepeatCount(5); // animation repeat count 

img.startAnimation(animation); // start animation 
+0

但它不會讓img從左側開始。我需要它就像它一樣向右走,然後出現在左側,看起來像繼續。 –

+0

它像從左到右的循環? – HsRaja

+0

我更新了代碼,請試試這個。預先感謝 – HsRaja