Issue
I want for example 3 images to change every 2 or 3 seconds endlessly repeating the circle.
// 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
How can i do this. Show code pls.
Thank you in advance
Solution
You can set a Thread to run on a continuous loop when the Activity is created (onCreate). The Thread can include a delay, and can update the UI with the next image. However, note that "you cannot update the UI from any thread other than the UI thread or the 'main' thread." (https://developer.android.com/guide/components/processes-and-threads). Try this:
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();
}
}
Answered By - Jonathan Furminger
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.