我如何无休止地更改一些图像? - Java

How i can change few images endlessly? - Java

例如,我想要每 2 或 3 秒更改 3 个图像,不断重复圆圈。

// Like this:

ImageView background = (ImageView)findViewById(R.id.main_background2);
background.setBackgroundResource(R.drawable.main_background1);
background.setBackgroundResource(R.drawable.main_background2);
background.setBackgroundResource(R.drawable.main_background3);

// And do something further

我该怎么做。请显示代码。

提前致谢

您可以在创建 Activity (onCreate) 时在连续循环中将线程设置为 运行。 Thread 可以包含一个延迟,并且可以用下一张图像更新 UI。但是,请注意“您不能从 UI 线程或 'main' 线程以外的任何线程更新 UI。”(https://developer.android.com/guide/components/processes-and-threads).试试这个:

    import androidx.appcompat.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.ImageView;

    public class MainActivity extends AppCompatActivity {

    ImageView background;
    public int imgCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        background = (ImageView)findViewById(R.id.imageView);
        imgCount = 1;
        runThread();
    }

    private void runThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // set thread to run on a continuous loop
                while (true) {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    imgCount++;
                    if (imgCount > 3) imgCount = 1;

                    // UI must be updated on the UI thread
                    background.post(new Runnable() {
                        public void run() {

                            switch (imgCount) {
                                case 1:
                                    background.setImageResource(R.drawable.main_background1);
                                    break;
                                case 2:
                                    background.setImageResource(R.drawable.main_background2);
                                    break;
                                case 3:
                                    background.setImageResource(R.drawable.main_background3);
                                    break;
                            }
                        }
                    });
                }
            }
        }).start();
    }
}