I have the following problem: I have an image in my App and the position shall change dynamically. The following code works already:
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
image.setLayoutParams(layoutParams);
image.setPadding(startX, startY, 0, 0);
image.setVisibility(View.VISIBLE);
for (int i=0; i<10; i++) {
startX+=10;
image.setPadding(startX, startY, 0, 0);
try {
Thread.sleep(1000);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
The problem is, that the image position is immediately changed to the final position, so I added the Thread.sleep lines. However, now the thread sleeps for 10x 3s and then the image changes to the final position. I also tried doing it in a new thread which didn't work as well.
Any thoughts on how I could reach my goal? I am happy for any solutions or input.
You could use a combination of Handler
and Runnable
to achieve this behaviour :
Step 1 : define your Handler and Runnable
Handler handler = new Handler();
Runnable refreshRunnable = new Runnable() {
@Override
public void run() {
refreshView();
}
}
Step 2 : Here's your refreshView function :
private void refreshView() {
count ++; //Variable initialized at 0 in your class
if (count < 10) {
startX += 10;
dotGreen.setPadding(startX, startY, 0, 0);
dotGreen.invalidate();
handler.postDelayed(refreshRunnable, 1000);
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments