How to imlement ZoomPinch Gesture in Fragment

2019-07-16 21:59发布

问题:

i had used ScaleGestureDetector. I used this code but it doesnt work in fragment and also it doesnt shows any error Please anyone can help me with this thanx in advance but when i use the same code in activity it works perfectly

public class Fragment2 extends Fragment {
ImageView imgZoom;
Matrix matrix = new Matrix();
float scale = 1f;
ScaleGestureDetector SGD;

// Keep all Images in array
         Integer[] mThumbIds = {
                R.drawable. car1, R.drawable.car2,
                R.drawable.car3, R.drawable.car4,
                R.drawable.car5,R.drawable.car6,
                R.drawable.car7,R.drawable.car8,
                R.drawable.car9,R.drawable.car10,
                R.drawable.car11,R.drawable.car12
                };



   @Override
   public View onCreateView(LayoutInflater inflater,
      ViewGroup container, Bundle savedInstanceState) {
       /**
           * Inflate the layout for this fragment
           */
       View view = inflater.inflate(R.layout.fragment2,container,false);

      //Sets the title of the Bar
      final ActionBar bar = getActivity().getActionBar();
      bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
      bar.setTitle("Pinch to zoom");

      //Recives the value of position sent from Fragment1
      int pos=getArguments().getInt("position");

      Button btnBack=(Button)view.findViewById(R.id.btnBack);

      imgZoom=(ImageView)view.findViewById(R.id.imageViewZoom);
      imgZoom.setImageResource(mThumbIds[pos]);
      SGD = new ScaleGestureDetector(view.getContext(),new ScaleListener());

      btnBack.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
             Intent mainScreen = new Intent(getActivity(), MainActivity.class);
             startActivity(mainScreen);
        }
    });

      return view;
   }
   public boolean onTouchEvent(MotionEvent ev) {
      SGD.onTouchEvent(ev);
      return true;
   }

   private class ScaleListener extends ScaleGestureDetector.
   SimpleOnScaleGestureListener {
   @Override
   public boolean onScale(ScaleGestureDetector detector) {
      scale *= detector.getScaleFactor();
      scale = Math.max(0.1f, Math.min(scale, 5.0f));
      matrix.setScale(scale, scale);
      imgZoom.setImageMatrix(matrix);
      return true;
   }
}

}

回答1:

Try this. It work for me.

view.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            SGD.onTouchEvent(motionEvent);
            return true;
        }
    });