android - 触摸屏幕时移动 View

标签 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开发的新手,我可能完全错了。
谢谢您的帮助 !
注意:我打算对按钮算法进行随机移动,动画是不够的。

最佳答案

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

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

关于android - 触摸屏幕时移动 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34754593/

相关文章:

python-3.x - iPython 笔记本中的动画

Android - 卡片 View 的动态大小

android - HTML5 视频在浏览器中有效 - 但在 Android 模拟器中无效

android - 通过单击按钮直接发送电子邮件 android

c# - 什么时候使用 Thread.Sleep() 是明智的?

c++ - 在 C++ 中,如何使用多个线程读取一个文件?

android - 安全取消后台线程中的 ORMLite 写入

c# - 如何在路径上设置渐变动画以在 WPF/WCF 应用程序中可视化数据流

java - 如何使用 "LIKE"和 "%"检查 android 中变量的相似性(Java 代码)

jquery - Javascript - 为什么这个函数循环两次?