当我将一个片段(全屏显示,背景#77000000)显示在另一个片段(我们称之为main)之上时,我的主片段仍然会对点击做出反应(即使我们看不到它,我们也可以单击按钮)。

问题:如何防止点击第一个(主)片段?

EDIT

不幸的是,我不能只是隐藏主片段,因为我在第二个片段上使用透明的背景(所以,用户可以看到后面的位置)。


当前回答

将第二个片段视图上的clickable属性设置为true。视图将捕获事件,这样它就不会被传递给主片段。因此,如果第二个片段的视图是一个布局,这将是代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true" />

其他回答

将第二个片段视图上的clickable属性设置为true。视图将捕获事件,这样它就不会被传递给主片段。因此,如果第二个片段的视图是一个布局,这将是代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true" />

只需添加clickable="true"和focusable="true"到父布局

 <android.support.constraint.ConstraintLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:clickable="true"
      android:focusable="true">

      <!--Your views-->

 </android.support.constraint.ConstraintLayout>

如果你正在使用AndroidX,试试这个

 <androidx.constraintlayout.widget.ConstraintLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:clickable="true"
      android:focusable="true">

          <!--Your views-->

 </androidx.constraintlayout.widget.ConstraintLayout>

解决方法很简单。在我们的第二个片段(与我们的主片段重叠)中,我们只需要捕捉onTouch事件:

@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstance){
    View root = somehowCreateView();

    /*here is an implementation*/

    root.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });
    return root;
}

你需要添加android:focusable="true"与android:clickable="true"

可点击意味着它可以通过指针设备点击,也可以通过触摸设备点击。

可聚焦意味着它可以从键盘等输入设备获得焦点。键盘等输入设备不能根据输入本身决定将输入事件发送到哪个视图,所以它们将它们发送到有焦点的视图。

方法1:

你可以添加到所有的片段布局

android:clickable="true"
android:focusable="true"
android:background="@color/windowBackground"

方法2:(编程)

从FragmentBase等扩展所有片段。然后将此代码添加到FragmentBase

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getView().setBackgroundColor(getResources().getColor(R.color.windowBackground));
    getView().setClickable(true);
    getView().setFocusable(true);
}