我在布局的中心创建了一个宽度为 50dp 的按钮。如果我触摸布局最左端的屏幕(没有按钮的地方)并按住(继续按下)直到我到达按钮center 然后它应该检测到触摸。我该怎么做。我已经尝试了 onCLicklistener() 和 onTouchListener() 但我仍然无法检测到触摸。 基本上就像手势,但我认为按钮有一种检测方式。
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// Toast text : entered within button
return false;
}
}))
最佳答案
如果我们将 Click 或 Touch 监听器设置为中心宽度为 50dp 的 Button,则只有当用户从按钮开始单击/触摸时,监听器才会收到回调。
在您的问题案例中,您从外部开始点击/触摸并进入按钮。
因此,按钮监听器不会从 Android Framework 获得回调
为了您的工作要求,我们需要添加一些逻辑,我已尝试在此处添加:
activity_main.xml :
<RelativeLayout android:id="@+id/parentLayout" ... >
<Button android:id="@+id/buttonCenter ... />
</RelativeLayout>
MainActivity.java :
// apply touch listener to parentLayout
button = (Button) findViewById(R.id.buttonCenter);
parent = (RelativeLayout) findViewById(R.id.parentLayout);
parent.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("tag","in onTouch...");
checkTouch(event);
return true;
}
});
// check if touch entered button area
// save button left, right, top and bottom edge
// update : This is API i found on google documentation
float[] params;
button.getLocationOnScreen(params);
public void checkTouch(MotionEvent event) {
x = event.getX();
y = event.getY();
if(x >= param[0] && x <= (param[0]+button.getWidth())) {
if(y >= param[1] && y <= (param[1]+button.getHeight())) {
Log.d("tag","this touch is in button area");
// do what you want to do when touch/click comes in button area
}
}
}
关于android - 当您在按钮上移动时如何检测触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29159288/