我已經通過了stackoverflow和所有類似的答案 - 但發現它們沒有用。更改Android線程上的圖像
任何人都可以請指出爲什麼這不工作?應該很簡單:每6秒更新一次圖像(每隔3分鐘更新一次,但測試時間爲6秒)。
代碼的作用是 - 逐步瀏覽4個圖像中的每一個,但不會更改圖像。但是當它到達最後的圖像時 - 它確實會改變它(??)。
問題:
- 這有什麼錯呢?
- 它爲什麼只更新最後一張圖片?
- 如果我只是通過一個「帖子」來處理程序而不是「postDelayed」來開始代碼 - 平板電腦只是停留在黑屏。爲什麼我必須延遲啓動代碼才能使其工作?
int currentIndex = 0;
boolean start = false;
ImageView descriptionImage;
private Runnable timerRunnable;
long startTime = 0;
private Handler handler;
int[] pictureIds = new int[]{R.drawable.hang, R.drawable.dog, R.drawable.coffee, R.drawable.about};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pictureDescription = new ArrayList<String>();
handler = new Handler(Looper.getMainLooper());
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_picture_test, container, false);
descriptionImage = (ImageView) v.findViewById(R.id.iv_picture);
return v;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
start();
}
private void start() {
start = true;
startTime = System.currentTimeMillis();
loadImage();
timerRunnable = new Runnable() {
@Override
public void run() {
while (start) {
long time = System.currentTimeMillis() - startTime;
float mins = (float) time/(60 * 1000);
if (mins >= 0.1f) {
startTime = System.currentTimeMillis();
if (currentIndex < pictureIds.length) {
currentIndex++;
loadImage();
}
}
}
}
};
handler.postDelayed(timerRunnable, 1000);
}
private void loadImage() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (currentIndex < pictureIds.length) {
descriptionImage.setImageResource(pictureIds[currentIndex]);
} else {
start = false; // finish
}
}
});
}
謝謝!
編輯:如果我將它發佈到imageview線程,而不是處理程序,則不起作用。
descriptionImage.postDelayed(timerRunnable,1000);
你的代碼不是用這個'while(start)'循環掛起UI線程嗎? –
除了你得到的這兩個答案之外,別忘了在你的片段的onPause中調用Handler#removeCallback。 –
順便說一下,'runOnUiThread(action)'相當於'uiHandler。交的(動作);'。既然你已經有UI處理器,爲什麼'getActivity()。runOnUiThread()'? –