我正在使用TabView
,在其中,我正在使用Fragment
加载每个选项卡。我希望在用户触摸任何片段时获得Touch
事件。
片段代码
public MobileBankingFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
context = (FragmentActivity) super.getActivity();
view = inflater.inflate(R.layout.fragment_mobile_banking, container, false);
alarm = new TimerReceiver();
init(view);
touchListener(view);
return view;
}
private void touchListener(View view) {
layout= (FrameLayout) view.findViewById(R.id.fragmentMobileBanking);
layout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Toast.makeText(context, "you just touch the screen :-)", Toast.LENGTH_SHORT).show();
return true;
}
});
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Toast.makeText(context, "you just touch the screen :-)", Toast.LENGTH_SHORT).show();
startTheTimerForTenSecond();
return true;
}
});
}
这里我尝试用两种方法来获取touch事件,一种是通过event,另一种是通过布局的id,但是我没有成功。
4条答案
按热度按时间yc0p9oo01#
它对我有效:
当您触摸整个碎片时,它会倾听
8e2ybdfx2#
您必须将ViewPager子类化并覆盖
interceptTouchEvent()
和onTouchEvent()
,以区分滑动手势和触摸片段事件。https://developer.android.com/training/gestures/viewgroup.htmlxwbd5t1u3#
你只需要在你的
fragments xml
中加上′ ′ focusable=“true”和clicable="true"
。az31mfrm4#
与@sockeqwe给出的答案类似,但有更多细节。您可能会将Fragment添加到Application类的某个片段容器中。假设您使用FrameLayout(从ViewGroup派生)来实现此目的。然后您需要从FrameLayout派生您自己的类。这将完成整个工作:
然后在应用程序xml(而不是片段xml)中使用此自定义FrameLayout(或任何其他片段容器)。