1

I want to move a view on touch and when the user unholds this view, it is started an animation which moves my view to the end of its parent.

This is my layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/time_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

<AbsoluteLayout
    android:id="@+id/slide_layout"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:layout_margin="20dp"
    android:background="#0000FF" >

    <View
        android:id="@+id/slide_to_pause"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="#00FFFF" />
</AbsoluteLayout>
</RelativeLayout>

This is how I set the view to move in my onCreate:

slideView = ((View) findViewById(R.id.slide_to_pause));
slideView.setOnTouchListener(this);

This is how I move the view and starts the animation:

@Override
public boolean onTouch(View view, MotionEvent event) {
    AbsoluteLayout.LayoutParams layoutParams = (AbsoluteLayout.LayoutParams) view.getLayoutParams();

    switch (event.getAction() & MotionEvent.ACTION_MASK) {

    case MotionEvent.ACTION_DOWN:
        mX = event.getRawX();
        break;

    case MotionEvent.ACTION_UP:
        int endOfAnimation = findViewById(R.id.slide_layout).getWidth() - view.getWidth();
        mSlideAnimation = new TranslateAnimation(0, endOfAnimation - layoutParams.x, 0, 0);
        mSlideAnimation.setDuration(1000);          
        view.startAnimation(mSlideAnimation);
        Log.d(TAG, "endOfAnimation = " + layoutParams.x + " | " + endOfAnimation);
        break;

    case MotionEvent.ACTION_MOVE:
        layoutParams.x = (int) event.getRawX();         
        view.setLayoutParams(layoutParams); 

        break;
    }
    return true;
}

The problem is that when the view arrives at the end it comes back to a point in the midle of the screen, which is the point where the user unholds the view. How can I fix this? Thank you!

androidevil
  • 8,400
  • 12
  • 39
  • 78

2 Answers2

3

You need to use

mSlideAnimation.setFillAfter(true);

to make it not revert back to the start.

If that doesn't work you might have to follow the suggestion on Animation.setFillAfter/Before - Do they work/What are they for?

Community
  • 1
  • 1
John Boker
  • 78,333
  • 17
  • 93
  • 129
1

You can simulate animation manually (move views yourself, without animation framework) by using

View.offsetLeftAndRight(int offset)
View.offsetTopAndBottom(int offset)
Korniltsev Anatoly
  • 3,595
  • 2
  • 24
  • 33