setOnTouchListener不适用于android Fragment

时间:2015-04-09 10:26:13

标签: android android-fragments fragment ontouchlistener tabview

我正在使用TabView,在Tab中,我使用Fragment加载每个tab.Now我想在用户触摸任何片段时获取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;
        }
    });
}

这里我尝试以两种方式获取触摸事件,一种是事件,另一种是布局的ID。但没有运气。此代码没有错误,但也没有输出。
帮帮我。

3 个答案:

答案 0 :(得分:2)

它适用于我:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_take_attendance, container, false);
    touchListener(view);
    ..
}
 private void touchListener(View view) {
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getActionMasked() == MotionEvent.ACTION_DOWN){
                    Toast.makeText(getActivity(), "you just touch the screen :-)", Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        });
    }

当你触摸整个片段时它会监听

答案 1 :(得分:1)

您必须继承ViewPager并覆盖interceptTouchEvent()onTouchEvent()以区分滑动手势和触摸片段事件。 https://developer.android.com/training/gestures/viewgroup.html

答案 2 :(得分:0)

您需要做的就是在您的clicable="true"中添加``focusable =“ true''和fragments xml