setOnTouchListener is not working for android Fragment

Shafiq Ullah Shohag picture Shafiq Ullah Shohag · Apr 9, 2015 · Viewed 12.6k times · Source

I am using TabView and in Tab ,I am using Fragment to load each tab.Now I want to get the Touch event when user touch any of the fragment. I am giving One of my Fragment code

 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;
        }
    });
}

here i try to get the touch event in two ways, one by event, another by the id of the layout.But no luck. This code gives no error, but no output also.
Help me.

Answer

Jemshit Iskenderov picture Jemshit Iskenderov · Apr 9, 2015

It works on me:

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;
            }
        });
    }

It listens when you touch whole fragment