如何在Android中以编程方式将按钮向左或向右移动

7
我想通过获取按钮的坐标并逐个增加或减少它们来实现按钮动画效果,使按钮可以向左移动然后回到右侧。
4个回答

9

使用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()可能会起作用...


我不知道为什么,但是button.getTop()和button.getLeft()都返回值0。 - Hisham Muneer
谢谢 @D-32,TranslateAnimation工作得非常好,按钮正在移动。 - Hisham Muneer
你能把带有按钮的xml放到你的问题中吗? - D-32

4

我不确定这是否能帮到您,但我曾遇到同样的问题。我可以使用以下方法解决:setTranslationX(float)和setTranslationY(float)

您可以像这样使用它:

Button button = (button) findViewById(your id); 
button.setTranslationX(a float value);

这里是提供更多信息的Android文档http://developer.android.com/reference/android/view/View.html#attr_android:translationX

。它涉及到IT技术,可以帮助你更好地理解。


1
当按钮被点击时图片从左向右移动,你也可以在片段中使用这段代码。 在片段的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;

1
   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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接