多个Fragment叠加点击穿透

当Fragment栈中有多个add Fragment时,点击最上层Fragment时的空白处,如果对应的下层Fragment中存在按钮或其他事件,那么奇妙的事情就发生了,会穿透点击到下方的事件,不可否认,这是我们不愿意看到的。 
究其原因:Fragment的本质就是一个View布局的管理器,当Fragment attach到Activity时,其实就是把Fragment#onCreateView()返回的View,替换掉(如果是用replace)FragmentTransaction#replace中指定的View,或者添加到(如果是add)FragmentTransaction#add()中指定的ViewGroup里面。 
当我们以层叠方式显示多个Fragment时,通常的做法就是弄一个FrameLayout,然后每次把Fragment add到此布局。因此,这时Activity的页面布局树实际上就是一个FrameLayout里面包含几个View。 
所以,当点击上面Fragment的空白区域时,如果事件没被吃掉,就会向下传递。 
解决方案: 
创建BaseFragement


public abstract class CJBaseFragment extends BaseFragment implements View.OnTouchListener {

public SweetAlertDialog pDialog;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

pDialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#FF4081"));
pDialog.setTitleText("正在加载中...");
pDialog.setCancelable(false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// 拦截触摸事件,防止泄露下去
view.setOnTouchListener(this);
}

@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
}


 其他Fragment可以继承CJBaseFragment这会让根布局把点击事件吃掉,以防止事件会继续传递下去,造成上面的情况。
原文地址:https://www.cnblogs.com/johnlis/p/6030661.html