OnTouch事件适用于我项目中的Coordinator布局,但不适用于底部导航视图。我不知道为什么,它应该适用于视图,并且底部导航视图是FrameLayout的子类,而FrameLayout是查看。
onTouchListener的代码:
bottomNavigationView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_UP){ //if the thumb is pulled up from the screen
// Do what you want
Log.d(TAG, "onTouch: up");
return true;
}
else if(motionEvent.getAction() ==MotionEvent.ACTION_DOWN){
Log.d(TAG, "onTouch: down");
// Construct a rect of the view's bounds
rect = new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
return true;
}
if(motionEvent.getAction() == MotionEvent.ACTION_MOVE){
if(!rect.contains(view.getLeft() + (int) motionEvent.getX(), view.getTop() + (int) motionEvent.getY())){
// User moved outside bounds
Log.d(TAG, "onTouch: out of bound");
}
}
return false;
}
});
这是xml布局,其中包含协调器布局和底部导航视图:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="512dp"
app:layout_constraintBottom_toTopOf="@+id/bottom_navigation"
app:layout_constraintTop_toTopOf="parent">
<!-- include main content -->
<include
layout="@layout/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Adding bottom sheet after main content -->
<include layout="@layout/bottom_sheet" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:itemBackground="@color/colorPrimary"
android:background="@color/colorPrimary"
app:itemIconTint="@android:color/white"
app:itemTextColor="@android:color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:elevation="10dp"
app:menu="@menu/bottom_nav_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>