Set OnTouchListener for Fragment

6.4k Views Asked by At

I have an application that have multiple fragments

For each fragment I want to perform some operation when touching that fragment

I have a fragment that draws a bitmap for me and I want this fragment to be full screen when touching The fragment has an image view that sets it to the bitmap I tried setting OnTouchListener inside the fragment for the view but I do not want that because each time the user press on the screen it will Start the activity even if it is already on full screen How can I add the OnTouchListener in my main activity for the fragment

Here is my code

in Main Activity I'm doing this

 public class MainActivity extends Activity  {
                     DrawBitmap drawView;           
                     drawView = (DrawBitmap ) getFragmentManager().findFragmentById(R.id.drawid);

                    }

in DrawBitmap class which is my fragment

   public class DrawBitmap extends Fragment  {

    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.imgid, container, true);

    v.setOnTouchListener(new View.OnTouchListener() {

        @Override
          public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();
              switch(action){
                  case MotionEvent.ACTION_DOWN:

                      Intent intent = new Intent(getActivity(), SecondActivity.class);
                      startActivity(intent);
                              break;

              }

              return false;
          }

    });
    return v;


}

  }

in SecondActivity

                public class SecondActivity extends Activity  {
                     DrawBitmap drawView;           
                     drawView = (DrawBitmap ) getFragmentManager().findFragmentById(R.id.drawid_full);

                    }

I want to be able to add OnTouchListener for drawView in Main Activity

1

There are 1 best solutions below

0
On

A fragment isn't a view and you can't add this kind of listeners directly on them.

A solution would be to override a "key pressed" style method hook and throw your own events. Unfortunately, fragments don't have this hook neither.

So, the last option, that should perfectly work, would be to add the listener on the view that your fragment returns during the method getView() (i.e the root view of your fragment). You will then have to deal a bit with event consumption inside the tree view hierarchy but it should work.