【发布时间】:2019-05-09 13:56:17
【问题描述】:
我有一个活动,用户可以在其中看到关于我正在尝试开发的简单应用程序的“关于”。我正在使用“Android About Page”来显示它,但另外我想检测屏幕上的点击次数,以便在检测到正确的点击次数时会出现 Toast 消息……有点像复活节彩蛋: ) 我面临的问题是没有触发触摸事件......这是我正在使用的代码:
public class About extends AppCompatActivity {
@Override
public void onTouchEvent(MotionEvent event) {
Log.i("LOG_RESPONSE", "Screen touched!");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
//// other code
}
}
这是我的 XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".About">
<View
android:id="@+id/myView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
没有错误,它什么也不做。
按照建议使用 onTouch() 进行编辑:
public class About extends AppCompatActivity {
View test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
test = (View)findViewById(R.id.myView);
test.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.i("LOG_RESPONSE", "Screen touched!");
return false;
}
});
//// other code
}
}
这样应用就会崩溃:
Caused by: java.lang.NullPointerException
编辑 2 - 它不再崩溃,但没有识别到触摸:
public class About extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
View test = findViewById(R.id.layer);
Log.i("LOG_RESPONSE", test.toString());
test.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.i("LOG_RESPONSE", "Screen touched!");
return false;
}
});
}
【问题讨论】:
标签: java android android-studio