我希望通过获取坐标来设置按钮的动画,然后逐个增加或减少它们,以便按钮可以向左移动然后向右移动。
答案 0 :(得分:8)
使用TranslateAnimation:
TranslateAnimation animation = new TranslateAnimation(start_x, start_y, end_x, end_y);
animation.setDuration(1000); // duartion in ms
animation.setFillAfter(false);
button.startAnimation(animation);
我不知道你怎么能得到它的位置,button.getTop()和button.getLeft()可以工作......
答案 1 :(得分:3)
不确定这是否会对您有所帮助,但我遇到了同样的问题,我能够使用这些方法来做到这一点,setTranslationX(float)setTranslationY(float)
你可以像这样使用它
Button button = (button) findViewById(your id);
button.setTranslationX(a float value);
这里提供了更多信息的http://developer.android.com/reference/android/view/View.html#attr_android:translationX
的Android文档答案 2 :(得分:0)
Solution for those who are looking for left to right animation)
TranslateAnimation animation = new TranslateAnimation(0.0f, 0.0f, 0.0f, 1500.0f); // new TranslateAnimation (float fromXDelta,float toXDelta, float fromYDelta, float toYDelta)
animation.setDuration(1500); // animation duration
animation.setRepeatCount(1); // animation repeat count
animation.setFillAfter(false);
your_view .startAnimation(animation);//your_view for mine is imageView
Solution for those who are looking for repeated animation(for eg. left to right and right to left)
TranslateAnimation animation = new TranslateAnimation(0.0f, 0.0f, 0.0f, 1500.0f); // new TranslateAnimation (float fromXDelta,float toXDelta, float fromYDelta, float toYDelta)
animation.setDuration(1500); // animation duration
animation.setRepeatCount(4); // animation repeat count
animation.setRepeatMode(2); // repeat animation (left to right, right to left)
animation.setFillAfter(true);
your_view .startAnimation(animation);//your_view for mine is imageView
答案 3 :(得分:0)
单击按钮时,图像从左向右移动 您也可以将此代码用于片段。
将此代码插入onCreateView中以获取片段或直接使用按钮侦听器。
View view = inflater.inflate(R.layout.fragment_move,container,false);
mBtnMove = view.findViewById(R.id.btn_move);
mImageMove = view.findViewById(R.id.imv_move);
mBtnMove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
float start_x_axis = 0; // initialize the axis value start from and end
float start_y_axis = 1000;
float end_x_axis = 0;
float end_y_axis = 0;
TranslateAnimation animation = new TranslateAnimation(start_x_axis, start_y_axis, end_x_axis, end_y_axis);
animation.setDuration(2500); // Duration of image to move from left to right
mImageMove.startAnimation(animation);
}
});
return view;