1

我的 xml 文件中有一些ImageViews。在我的代码部分中,我想根据自己的意愿移动图像。为此,我已经完成event.getx()event.getY() 然后使用imageView.layout(). 此过程不起作用。我怎样才能移动那个图像?

4

1 回答 1

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;
        }
    });
于 2013-11-30T23:37:06.040 回答