使用计时器在图像视图中显示随机图像会出错

Displaying random images in image view using timer gives error

我是 Android 的新手。我正在尝试制作一个 imageView,它会在几秒钟后更改背景图像。我尝试了以下代码,但它抛出异常。

MainActivity.java

package com.example.testapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.content.res.TypedArray;

import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.IOException;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

   MediaPlayer mp;
   int index = R.drawable.picture1_1;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       Toast.makeText(this,"Test 1",Toast.LENGTH_SHORT).show();

       final ImageView imageView = findViewById(R.id.imageView);
       mp = MediaPlayer.create(this, R.raw.click); 
       final int resId[] = {R.drawable.picture1_1, R.drawable.picture1_2, R.drawable.picture2_1, R.drawable.picture2_2, R.drawable.picture3_1, R.drawable.picture3_2, R.drawable.picture4_1, R.drawable.picture4_2, R.drawable.picture5_1, R.drawable.picture5_2, R.drawable.picture6_1, R.drawable.picture6_2, R.drawable.picture7_1, R.drawable.picture7_2, R.drawable.picture8_1, R.drawable.picture8_2, R.drawable.picture9_1, R.drawable.picture9_2, R.drawable.picture10_1, R.drawable.picture10_2};

       Timer timer = new Timer();
       timer.scheduleAtFixedRate(new TimerTask() {
           @Override
           public void run() {

               Random rand = new Random();
               index = rand.nextInt((resId.length- 1) - 0 + 1) + 0;

               imageView.setImageResource(resId[index]);
           }
       }, 5000, 5000);

   }
   public void Clicked(View view){
       Toast.makeText(this,"Hello User",Toast.LENGTH_SHORT).show();
       mp.start();
   }

}

activitymain.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/constraintLayout"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:onClick="Clicked"
  tools:context=".MainActivity">

  <ImageView
      android:id="@+id/imageView"
      android:layout_width="631dp"
      android:layout_height="909dp"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      app:srcCompat="@drawable/picture1_2"
      android:foreground="?android:attr/selectableItemBackgroundBorderless"
      android:contentDescription="@string/todo" />

</androidx.constraintlayout.widget.ConstraintLayout>

代码运行 5 秒,之后计时器被激活,应用程序崩溃并出现以下错误:

  E/AndroidRuntime: FATAL EXCEPTION: Timer-0
  Process: com.example.testapplication, PID: 12062
  android.content.res.Resources$NotFoundException: Unable to find resource ID #0x3
  at android.content.res.ResourcesImpl.getResourceName(ResourcesImpl.java:276)
  at android.content.res.Resources.getResourceName(Resources.java:2076)
  at com.example.testapplication.MainActivity.run(MainActivity.java:68)
  at java.util.TimerThread.mainLoop(Timer.java:562)
  at java.util.TimerThread.run(Timer.java:512)```

您不能从主线程以外的线程对 UI 组件应用任何更改。使用下面的代码

timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {

        runOnUiThread(new Runnable() {

        @Override
        public void run() {
            Random rand = new Random();
            index = rand.nextInt((resId.length- 1) - 0 + 1) + 0;

            imageView.setImageResource(resId[index]);
        }          
    });
    }
}, 5000, 5000);

希望能帮到你