例如,我希望每 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
我怎樣才能做到這一點。請顯示代碼。
先感謝您
uj5u.com熱心網友回復:
您可以在創建 Activity (onCreate) 時將 Thread 設定為在連續回圈上運行。執行緒可以包含延遲,并且可以使用下一個影像更新 UI。但是,請注意“您不能從 UI 執行緒或‘主’執行緒以外的任何執行緒更新 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();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/450065.html
