我正试图围绕Android处理触摸事件的方式来围绕我的脑袋,并且我对此感到困惑。 据我所知,如果视图元素的onTouch()
事件设置为true,这意味着该元素已准备好处理该触摸事件,即它消耗触摸事件。
如果是这样,在下面的代码片段中,运行后,锁定,当它返回true时,不允许我们更改收音机组的选择
我确定它是因为我不太熟悉Android触摸事件如何工作。有人可以为我正确地总结它。并解释为什么返回true
为onTouch()
事件阻止我们选择新项目。Android - 当单选按钮的ontouch()方法设置为true时会发生什么
package com.examples.customtouch;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
/**
* Created by Dave Smith
* Double Encore, Inc.
* Date: 9/25/12
* TouchListenerActivity
*/
public class TouchListenerActivity extends Activity implements View.OnTouchListener {
/* Views to display last seen touch event */
CheckBox mLockBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.touch_listener);
mLockBox = (CheckBox) findViewById(R.id.checkbox_lock);
findViewById(R.id.selection_first).setOnTouchListener(this);
findViewById(R.id.selection_second).setOnTouchListener(this);
findViewById(R.id.selection_third).setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
/*
* Consume the events here so the buttons cannot process them
* if the CheckBox in the UI is checked
*/
return mLockBox.isChecked();
}
private String getNameForEvent(MotionEvent event) {
String action = "";
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
action = "ACTION_DOWN";
break;
case MotionEvent.ACTION_CANCEL:
action = "ACTION_CANCEL";
break;
case MotionEvent.ACTION_MOVE:
action = "ACTION_MOVE";
break;
case MotionEvent.ACTION_UP:
action = "ACTION_UP";
break;
default:
return null;
}
return String.format("%s\n%.1f, %.1f", action, event.getX(), event.getY());
}
}
活动的XML文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<CheckBox
android:id="@+id/checkbox_lock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lock Selection" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/selection_first"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="First"/>
<RadioButton
android:id="@+id/selection_second"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Second"/>
<RadioButton
android:id="@+id/selection_third"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Third"/>
</RadioGroup>
</LinearLayout>
请注意,此代码段是从Dave Smith一个项目叫做Custom Touch Examples