java - 如何在 Android Studio 中连续移动对象
问题描述
按住按钮时如何在Android Studio中连续移动ImageView,但不再单击时停止?换句话说:如何检测按钮是否“未点击”或直接检测它是否被按住。感谢您的帮助
解决方案
要检测按钮是否被按下/释放(向下/向上),使用 TouchListener。
imageView = findViewById(R.id.image);
button = findViewById(R.id.button);
root_layout = findViewById(R.id.root_layout); //parent layout
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
float x = imageView.getX();
if(x > root_layout.getWidth())
x = 0;
else
x += 6; //Increase value of '6' to move the imageView faster
imageView.setX(x);
handler.postDelayed(this,0); //increase delay '0' if facing lag.
// This is the rate at which the x value of our imageView is being updated
}
};
button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
handler.post(runnable); //Start moving imageView
break;
case MotionEvent.ACTION_UP:
handler.removeCallbacks(runnable); //Stop moving imageView
break;
}
return true;
}
});
推荐阅读
- assembly - 如何在arm Assembly中乘以和除以奇数常数?
- javascript - Javascript Web Firebase 获取在本地运行但不在公共 IP 中运行的令牌
- java - 在 Netbeans 中关闭程序时将用户状态设置为注销
- angular - Angular 7 - 动态添加指令
- reactjs - 如何使用 Enzyme (Jest) 在 React Native 单元测试中测试 Elements 值
- excel - SUMIF EXCEL 2013 - 多个标准
- java - 在按钮单击时添加字段
- acrobat - 如何强制 Adobe Acrobat DC 以横向平铺输出?
- c# - Cortana - 检索以 wav 或 BLOB 格式提供的语音输入
- javascript - 从双重功能中获取变量