2017-03-27 97 views
1
final ImageView imageView = (ImageView) findViewById(R.id.imageView); 
      if (imageView != null) { 
       imageView.setOnTouchListener(new View.OnTouchListener() { 
        @Override 
        public boolean onTouch(View view, MotionEvent event) { 
         int eid = event.getAction(); 
         switch (eid) { 
          case MotionEvent.ACTION_MOVE : 
           ConstraintLayout.LayoutParams mParams = (ConstraintLayout.LayoutParams) imageView.getLayoutParams(); 
           int x = (int) event.getRawX(); 
           int y = (int) event.getRawY(); 
           mParams.leftMargin = x - 50; 
           mParams.topMargin = y - 50; 
           imageView.setLayoutParams(mParams); 
           break; 
          default : 
           break; 
         } 
         return true; 
        } 
       }); 
      } 

此代碼的工作:選擇圖像和移動圖像在屏幕上,但我想移動屏幕上的觸摸 形象,我想在屏幕上觸摸移動圖像:如何使用移動包含在RelativeLayout的所有意見如何在屏幕上移動圖像觸摸?

+0

請參閱Drop&Drag:https://developer.android.com/guide/topics/ui/drag-drop.html – Opiatefuchs

回答

0

例onTouch

public class MainActivity extends AppCompatActivity implements View.OnTouchListener { 
    private RelativeLayout mRelLay; 
    private float mInitialX, mInitialY; 
    private int mInitialLeft, mInitialTop; 
    private View mMovingView = null; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     mRelLay = (RelativeLayout) findViewById(R.id.relativeLayout); 

     for (int i = 0; i < mRelLay.getChildCount(); i++) 
      mRelLay.getChildAt(i).setOnTouchListener(this); 
    } 

    @Override 
    public boolean onTouch(View view, MotionEvent motionEvent) { 
     RelativeLayout.LayoutParams mLayoutParams; 

     switch (motionEvent.getAction()) { 
      case MotionEvent.ACTION_DOWN: 
       mMovingView = view; 
       mLayoutParams = (RelativeLayout.LayoutParams) mMovingView.getLayoutParams(); 
       mInitialX = motionEvent.getRawX(); 
       mInitialY = motionEvent.getRawY(); 
       mInitialLeft = mLayoutParams.leftMargin; 
       mInitialTop = mLayoutParams.topMargin; 
       break; 

      case MotionEvent.ACTION_MOVE: 
       if (mMovingView != null) { 
        mLayoutParams = (RelativeLayout.LayoutParams) mMovingView.getLayoutParams(); 
        mLayoutParams.leftMargin = (int) (mInitialLeft + motionEvent.getRawX() - mInitialX); 
        mLayoutParams.topMargin = (int) (mInitialTop + motionEvent.getRawY() - mInitialY); 
        mMovingView.setLayoutParams(mLayoutParams); 
       } 
       break; 

      case MotionEvent.ACTION_UP: 
       mMovingView = null; 
       break; 
     } 

     return true; 
    } 
} 
相關問題