gpt4 book ai didi

android - 触摸屏幕时移动 View

转载 作者:行者123 更新时间:2023-12-03 13:10:32 24 4
gpt4 key购买 nike

我有一个按钮,当用户触摸它时,我希望按钮开始移动。
触摸屏幕后,在相对布局上移动按钮(以固定速度)
我试图使用线程来产生运动。
这是减少到最低限度的代码,解决方案可能完全不同...
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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com