触摸屏幕时移动视图

时间:2016-01-12 22:01:44

标签: android multithreading animation 2d

我有一个按钮,当用户触摸它时,我希望按钮开始移动。

触摸屏幕后,在相对布局上移动按钮(固定速度)

我尝试使用线程来生成动作。

这里的代码减少到最小,解决方案可能完全不同......

FragmentGameBoard :包含RelativeLayout按钮的片段。这是一个片段,但在MainActivity中实际上可能是相同的

public class FragmentGameBoard extends Fragment {

    private MovingButton btn;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Instanciation du Layout fragment
        View view = inflater.inflate(R.layout.fragment_gameboard, container, false);
        btn = (MovingButton) view.findViewById(R.id.btn);

        btn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    //TODO Move button
                    btn.buttonThread.run();
                }
                return true;
            }
        });

        return view;
    }

MovingButton :尝试扩展按钮以使其自己的线程移动

public class MovingButton extends Button {

    public ButtonThread buttonThread;

    public MovingButton(Context context){
        super(context);
        buttonThread = new ButtonThread(this);
    }

    public MovingButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        buttonThread = new ButtonThread(this);
    }

    public MovingButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        buttonThread = new ButtonThread(this);
    }

}

ButtonThread :线程我尝试启动

public class ButtonThread implements Runnable {

    private MovingButton movingButton;

    public ButtonThread(MovingButton movingButton) {
        this.movingButton = movingButton;
    }

    public void run(){
        float x = movingButton.getX();
        float y = movingButton.getX();
        while(movingButton.getX()>5) {
            movingButton.setX(x - 1);

            try {
                synchronized (this) {
                    this.wait(5); // To have something like fps
                }
            } catch (InterruptedException ie) {
                System.out.println("interruption");
            }
        }
    }

}

我真的不知道该怎么做。它实际上是进入while循环(和循环)但按钮没有移动。 (我必须说我并不感到惊讶......)

我是Android开发的新手,我可能完全错了。

感谢您的帮助!

注意:我打算随机运动按钮算法,动画不够。

1 个答案:

答案 0 :(得分:0)

更新UI必须在主线程上调用。 如果你想移动你的按钮,使用属性动画是更好的方法。

ObjectAnimator.ofFloat(btn, "translationX", 0f, 360f).setDuration(1000).start();
相关问题