Reputation: 1595
I want to create an android project. Which there is a layout that I want it to move smoothly on another layout. I have tried to use thread in order to do this. But in the result of my code, the layout jumps to its final position and do not move smoothly from the offset to its destination.
abs1 = (AbsoluteLayout) findViewById(R.id.absoluteLayout2);
ImageButton ib1 = (ImageButton) findViewById(R.id.imageButton1);
ib1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Runnable r = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
display(100);
display(100);
display(100);
display(100);
display(100);
display(100);
display(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void display(int i) throws InterruptedException {
AbsoluteLayout.LayoutParams param = (AbsoluteLayout.LayoutParams) abs1
.getLayoutParams();
param.x = param.x + 10;
// param.y=param.x+20;
abs1.setLayoutParams(param);
if (Thread.interrupted()) {
throw (new InterruptedException());
}
Thread.sleep(i);
}
};
r.run();
main file:
<AbsoluteLayout
android:id="@+id/absoluteLayout2"
android:layout_width="107dp"
android:layout_height="308dp"
android:layout_x="10dp"
android:layout_y="12dp"
android:background="@color/red" >
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="0dp"
android:layout_y="0dp"
android:background="@null"
android:src="@drawable/calendar" />
Upvotes: 0
Views: 236
Reputation: 2127
Your Runnable
is actually running on Android's UI thread.
So sleep()
will block UI's drawing process, show the view on final position.
Use a Thread
to wrap it.
(new Thread(new Runnable() {
@Override
public void run() {
// your code
}
}
})).start();
Then, remember that updating views from non-UI thread is forbidden.
You should use runOnUiThread
to update views.
runOnUiThread(new Runnable() {
@Override
public void run() {
display(100);
}
}
Maybe, use Android's Animation class is a better way to do this.
Upvotes: 0
Reputation: 14435
EDIT: this is available starting from API 11
Just use an ObjectAnimator
for that:
ObjectAnimator moveToSide = ObjectAnimator.ofFloat(myView, "translationX", 0f, 400f);
moveToSide.setDuration(700);
moveToSide.start();
Just try it out with different float values. Now, it starts from it's original position to 400f along the X-axis.
Afterwards it will stay in this position. You could also add an AnimatorListener
if you want to do some stuff on the start or at the end.
moveToSide.addListener(new AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
}
@Override
public void onAnimationCancel(Animator arg0) {
}
});
Upvotes: 1