2015-04-18 68 views
0

我製作了一個數組,其中包含int中的所有圖像,並且我希望每隔3秒在imageView中更改這些圖像,我嘗試了所有可找到的解決方案,但顯示出一些錯誤,我無法弄清楚。如何在imageview中每n秒鐘更改一次圖像

的java文件(home.java)

/** 
* Created by sukhvir on 17/04/2015. 
*/ 
public class home extends android.support.v4.app.Fragment { 

    ImageView MyImageView; 
    int[] imageArray = { R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5 }; 

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     /** 
     * Inflate the layout for this fragment 
     */ 
     return inflater.inflate(R.layout.home, container, false); 
    } 
} 

XML文件(home.xml)

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <ImageView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/imageView" 
     android:layout_gravity="center_horizontal" /> 
</LinearLayout> 
+0

Yon可以簡單地使用Thread/Timer/CountDownTimer在每秒鐘更改圖像。 – SilentKiller

回答

3

最好的選擇來實現你的要求是你應該使用Timer來改變圖像每3秒如下。

// Declare globally 
private int position = -1; 

/** 
* This timer will call each of the seconds. 
*/ 
Timer mTimer = new Timer(); 
mTimer.schedule(new TimerTask() { 
    @Override 
    public void run() { 
     // As timer is not a Main/UI thread need to do all UI task on runOnUiThread 
     getActivity().runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
        // increase your position so new image will show 
       position++; 
       // check whether position increased to length then set it to 0 
       // so it will show images in circuler 
       if (position >= imageArray.length) 
        position = 0; 
       // Set Image 
       MyImageView.setImageResource(imageArray[position]); 
      } 
     }); 
    } 
}, 0, 3000); 
// where 0 is for start now and 3000 (3 second) is for interval to change image as you mentioned in question 
+0

我得到的位置錯誤 –

+0

@SukhvirThapar你面臨什麼錯誤? – SilentKiller

+0

紅色中的位置,無法解析符號'位置' –

0

首先定義一個可運行的

private Runnable runnable = new Runnable() { 

    @Override 
    public void run() { 
     changeImage(pos); 
    } 
}; 

不是創建一個處理程序

private Handler handler; 
handler = new Handler(Looper.getMainLooper()); 

在你changeImage方法

private void changeImage(int pos) { 
    yourImageView.setImageResource(imageArray[pos]); 
    handler.postDelayed(runnable, duration); 
} 

啓動和停止運行的有:

handler.postDelayed(runnable, duration); 
handler.removeCallbacks(runnable); 

我希望這能幫到你。祝你好運。