2012-04-25 71 views
1

我在我的xml文件中有一些ImageViews。在我的代码部分,我想根据我的意愿移动图像。为此,我完成了event.getx()event.getY(),然后使用imageView.layout()。这个过程不起作用。我如何移动该图像?如何重新定位ImageView

+0

检查这个问题 http://stackoverflow.com/questions/7168770/how-to-place-views-in-a-specific-location-xy-coordinates – birdy 2012-04-26 11:46:02

回答

1

我想这可能帮助:

package com.example.moveimageview; 


import android.os.Bundle; 
import android.app.Activity; 
import android.content.Context; 
import android.graphics.Canvas; 
import android.view.Menu; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.View.OnTouchListener; 
import android.widget.ImageView; 
import android.widget.RelativeLayout; 


public class MainActivity extends Activity { 

    ImageView im; 
    RelativeLayout rl; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     //getting the wrapper layout from the xml 
     rl = (RelativeLayout) findViewById(R.id.relative1); 

     //getting the ImageView from xml 
     im = (ImageView) findViewById(R.id.myImageView); 

     rl.setOnTouchListener(new OnTouchListener() { 

      @Override 
      public boolean onTouch(View v, MotionEvent e) { 
       // TODO Auto-generated method stub 
       if(e.getAction()==android.view.MotionEvent.ACTION_DOWN) 
       { 
        //sending the new coordinates to the method 
        //that will change the view's location 
        setImageViewLocation(e.getX(), e.getY()); 


       return true; 
       } 
       return false; 
      } 
     }); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

    private void setImageViewLocation(float x, float y) 
    { 
     //setting the coordinates 
     im.setX(x); 
     im.setY(y); 

     runOnUiThread(new Runnable() { 

      @Override 
      public void run() { 
       // TODO Auto-generated method stub 
       im.invalidate();//invoking the view onDraw 
      } 
     }); 

    } 
} 

(编辑)如果你想你的ImageView的周围,这里是这个(相同的代码之前刚刚与这个替换OnTouchListner)的onTouchListner代码:

rl.setOnTouchListener(new OnTouchListener() { 

     @Override 
     public boolean onTouch(View v, MotionEvent e) { 
      // TODO Auto-generated method stub 
      if(e.getAction()==android.view.MotionEvent.ACTION_DOWN) 
      { 
       //sending the new coordinates to the method 
       //that will change the view's location 
       setImageViewLocation(e.getRawX(), e.getRawY()); 


      return true; 
      } 

      if(e.getAction()==android.view.MotionEvent.ACTION_MOVE) 
      { 
       setImageViewLocation(e.getRawX(), e.getRawY()); 
       return true; 
      } 
      return false; 
     } 
    });