Reputation: 14246
I have an image button and associated click handler.
When I animate button (using translate animation) the button, obviously, changes it's position on screen.
But there is a problem: Android detects clicks when I touch initial button location and not the current.
How can I make Android respect actual location of the button?
fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/addButton"
android:src="@android:drawable/ic_input_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="plusButtonClick"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends ActionBarActivity
{
public void plusButtonClick(View v)
{
Toast.makeText(this, "Clicked!", Toast.LENGTH_SHORT).show();
animateButton(R.id.addButton, R.anim.anim_move);
}
private void animateButton(int buttonId, int animationId)
{
View button = findViewById(buttonId);
AnimationSet animationSet = (AnimationSet)AnimationUtils.loadAnimation(this, animationId);
animationSet.setAnimationListener(getStartingButtonsListener(button));
button.setVisibility(View.VISIBLE);
button.startAnimation(animationSet);
}
private Animation.AnimationListener getStartingButtonsListener(final View v)
{
return new Animation.AnimationListener()
{
@Override
public void onAnimationEnd(Animation arg0)
{
v.setVisibility(View.GONE);
}
};
}
}
anim_move.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="true"
android:fillAfter="true"
android:duration="1000">
<translate
android:fromXDelta="0"
android:toXDelta="180"
android:fromYDelta="0"
android:toYDelta="0"/>
</set>
Upvotes: 4
Views: 95
Reputation: 1639
Use onTouchEvent for your button. Moreover, give this onTouch implementation through java file, but not with the XML layout file. This is far better than using onClick event. See this : Triggering event when Button is pressed down in Android
Upvotes: 0
Reputation: 1743
The translate animation doesn't actually move your object, it just moves the image of it. You should reposition your button yourself at the end of the animation by editing its LayoutParams
Upvotes: 1
Reputation: 1352
I had a similar problem here : Button moves to different part of screen but can only press it at its initial spot?
The animation is animating the pixels, not the touch zones of a widget. You need to animate the properties as well : https://developer.android.com/guide/topics/graphics/prop-animation.html
Upvotes: 3