首页 > 其他分享 >android 拖拽图片&拖动浮动按钮到处跑

android 拖拽图片&拖动浮动按钮到处跑

时间:2023-04-07 10:04:49浏览次数:58  
标签:MotionEvent 拖动 到处跑 public int import android event


来自老外:

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent ;
import android.widget.AbsoluteLayout;
import android.widget.Button;

public class Drag_And_Drop extends Activity {
  /** Called when the activity is first created. */

  @Override
   public void onCreate(Bundle icicle) {
       super.onCreate(icicle);

       MyView tx = new MyView(this);
       tx.setText("Drag Me");
       AbsoluteLayout l = new AbsoluteLayout(this);

       AbsoluteLayout.LayoutParams p = new AbsoluteLayout.LayoutParams(
AbsoluteLayout.LayoutParams.WRAP_CONTENT,
AbsoluteLayout.LayoutParams.WRAP_CONTENT,10,10);
       l.addView(tx,p);
       setContentView(l);
  }
}
class MyView extends Button{

        public MyView(Context c){
           super(c);
        }

        @Override
        public boolean onMotionEvent(MotionEvent event) {
          int action = event.getAction();
          int mCurX = (int)event.getX();
          int mCurY = (int)event.getY();

          if ( action == MotionEvent.ACTION_MOVE ) {
             //this.setText("x: " + mCurX + ",y: " + mCurY );
              AbsoluteLayout.LayoutParams p = new
AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.WRAP_CONTENT,
AbsoluteLayout.LayoutParams.WRAP_CONTENT,this.mLeft + mCurX,this.mTop +
mCurY);
              this.setLayoutParams (p);

          }
          if ( action == MotionEvent.ACTION_UP ) {
            //this.setText("not moving");

          }
          return true;
        }

        @Override
        public void draw(Canvas canvas) {
          // TODO Auto-generated method stub
          super.draw(canvas);

        }

    }




拖拽图片效果



方法一:


import android.app.Activity;  
import android.os.Bundle;  
import android.view.MotionEvent;  
import android.view.View;  
import android.view.View.OnTouchListener;  
import android.widget.ImageView;  
public class DragSample01 extends Activity {  
    ImageView img;  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.drag_sample01);          
        img = (ImageView)findViewById(R.id.img_view);  
          
        img.setOnTouchListener(new OnTouchListener(){             
            private int mx, my;           
            public boolean onTouch(View v, MotionEvent event) {  
                switch(event.getAction()) {               
                case MotionEvent.ACTION_MOVE:  
                    mx = (int)(event.getRawX());  
                    my = (int)(event.getRawY() - 50);  
                      
                    v.layout(mx - img.getWidth()/2, my - img.getHeight()/2, mx + img.getWidth()/2, my + img.getHeight()/2);  
                    break;  
                }  
                return true;  
            }});  
    }  
}



方法二:


import android.app.Activity;  
import android.os.Bundle;  
import android.view.MotionEvent;  
import android.view.View;  
import android.view.View.OnTouchListener;  
import android.widget.ImageView;  
public class DragSample01 extends Activity {  
    ImageView img;  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.drag_sample01);          
        img = (ImageView)findViewById(R.id.img_view);  
          
        img.setOnTouchListener(new OnTouchListener(){             
            private float x, y;  
            private int mx, my;           
            public boolean onTouch(View v, MotionEvent event) {  
                switch(event.getAction()) {   
                case MotionEvent.ACTION_DOWN:  
                    x = event.getX();  
                    y = event.getY();  
                case MotionEvent.ACTION_MOVE:  
                    mx = (int)(event.getRawX() - x);  
                    my = (int)(event.getRawY() - 50 - y);  
                      
                    v.layout(mx, my, mx + v.getWidth(), my + v.getHeight());  
                    break;  
                }  
                return true;  
            }});  
    }  
}




拖动按钮到处跑


1. 布局文件


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:id="@+id/btn" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="拖动看看~~" />
</LinearLayout>



2. 代码



import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;

public class DraftTest extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		final Button btn = (Button) findViewById(R.id.btn);

		btn.setOnTouchListener(new OnTouchListener() {
			int[] temp = new int[] { 0, 0 };

			public boolean onTouch(View v, MotionEvent event) {

				int eventaction = event.getAction();

				int x = (int) event.getRawX();
				int y = (int) event.getRawY();

				switch (eventaction) {

				case MotionEvent.ACTION_DOWN: // touch down so check if the
					temp[0] = (int) event.getX();
					temp[1] = y - v.getTop();
					break;

				case MotionEvent.ACTION_MOVE: // touch drag with the ball
					v.layout(x - temp[0], y - temp[1], x + v.getWidth()
							- temp[0], y - temp[1] + v.getHeight());

//					v.postInvalidate();
					break;

				case MotionEvent.ACTION_UP:
					break;
				}

				return false;
			}

		});

	}
}




另一种:


import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;

public class DraftTest extends Activity {
	/** Called when the activity is first created. */

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		DisplayMetrics dm = getResources().getDisplayMetrics();
		final int screenWidth = dm.widthPixels;
		final int screenHeight = dm.heightPixels - 50;

		final Button b = (Button) findViewById(R.id.btn);

		b.setOnTouchListener(new OnTouchListener() {

			int lastX, lastY;

			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					lastX = (int) event.getRawX();
					lastY = (int) event.getRawY();
					break;
				case MotionEvent.ACTION_MOVE:
					int dx = (int) event.getRawX() - lastX;
					int dy = (int) event.getRawY() - lastY;

					int left = v.getLeft() + dx;
					int top = v.getTop() + dy;
					int right = v.getRight() + dx;
					int bottom = v.getBottom() + dy;

					if (left < 0) {
						left = 0;
						right = left + v.getWidth();
					}

					if (right > screenWidth) {
						right = screenWidth;
						left = right - v.getWidth();
					}

					if (top < 0) {
						top = 0;
						bottom = top + v.getHeight();
					}

					if (bottom > screenHeight) {
						bottom = screenHeight;
						top = bottom - v.getHeight();
					}

					v.layout(left, top, right, bottom);

					lastX = (int) event.getRawX();
					lastY = (int) event.getRawY();

					break;
				case MotionEvent.ACTION_UP:
					break;
				}
				return false;
			}
		});
	}
}




再一个,浮动按钮的实现。


主要功能:


点击按钮可以进行拖动;


当点击按钮时按钮会出现于所有按钮的最上方;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AbsoluteLayout;
import android.widget.Button;

public class HelloWorld2 extends Activity {
    /** Called when the activity is first created. */
	
	AbsoluteLayout mLayoutGroup = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        
        mLayoutGroup = new AbsoluteLayout(this);
        AbsoluteLayout.LayoutParams layoutParams = new AbsoluteLayout.LayoutParams
        (320, 480, 0, 0);
        
        setContentView(mLayoutGroup, layoutParams);
        
        Button button= new Button(this);
        button.setText("testButton");
        layoutParams = new AbsoluteLayout.LayoutParams(120, 60, 20, 20);
        mLayoutGroup.addView(button, layoutParams);
        button.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				//alert();
			}
		});
        button.setOnTouchListener(touchListener);
        
        final Button btButton = new Button(this);
        btButton.setText("测试按钮移动");
        layoutParams = new AbsoluteLayout.LayoutParams(120, 60, 20, 160);
        mLayoutGroup.addView(btButton, layoutParams);
        btButton.setOnTouchListener(touchListener);
    }
    
    OnTouchListener touchListener = new OnTouchListener()
    {
    	int temp[] = new int[]{0, 0};
		public boolean onTouch(View arg0, MotionEvent arg1) {
			// TODO Auto-generated method stub
			int eventAction = arg1.getAction();
			Log.e("testButtonMove", "OnTouchAction:"+eventAction);
			
			int x = (int)arg1.getRawX();
			int y = (int)arg1.getRawY();
			
			switch (eventAction) {
			case MotionEvent.ACTION_DOWN:
				
				temp[0] = (int)arg1.getX();
				temp[1] = (int)(y-arg0.getTop());	
				
				mLayoutGroup.bringChildToFront(arg0);
				arg0.postInvalidate();
				
				break;
			case MotionEvent.ACTION_MOVE:
				
				int left = x - temp[0];
				int top = y - temp[1];
				int right = left + arg0.getWidth();
				int bottom = top + arg0.getHeight();
				
				arg0.layout(left, top, right, bottom);
				arg0.postInvalidate();
				
				break;

			default:
				break;
			}
			
			return false;
		}
    };
    
    void alert()
    {
    	new AlertDialog.Builder(this)
    	.setNeutralButton("OK", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
		})
		.setTitle("test button")
		.setMessage("test test test!!!")
		.show();
    }
    
    
}





  • android 拖拽图片&拖动浮动按钮到处跑_xml

  • 大小: 11.6 KB
  • 查看图片附件

标签:MotionEvent,拖动,到处跑,public,int,import,android,event
From: https://blog.51cto.com/u_5454003/6174592

相关文章

  • 拖动一个控件在另一个控件(layout)上,并固定位置在几个位置显示
    实现效果:鼠标拖动btnSSS,SSS在水平的layout上移动。当鼠标抬起响应UP事件。SSS会自动移动到距离其最近的Btn上,与其重合。即SSS如图只存在五个固定的显示位置。SSS响应setOnTouchListener事件。在MotionEvent.ACTION_UP事件中,调用TranslateAnimation动画效果,将其从UP事件位置......
  • android打造的最简单计算器界面
    先看图:这里主要是锻炼一下TableLayout布局,注意其中的android:stretchColumns="0,1,2,3"属性,该属性可以控制每列的宽的权重,类似weight,由于这里4列都是“平等的”,所以是“0,1,2,3”,全部布局文件如下:<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:an......
  • android之简单数据存储Preference
    这里的持久化其实就是本地配置文件的读写,实现方法是通过Activity.getPreferences(int)获取SharedPreferences对象,然后操作配置文件的读写,值得注意的是以下几点:1)Activity.getPreferences(intmode)等价于Content.getSharedPreferences(Stringfilename,intmod......
  • Android存储用户登录信息最好的方式之一-Shared Preferences
    对于Android应用程序,存储用户登录信息的最佳方式是使用SharedPreferences。SharedPreferences是Android提供的一个轻量级存储机制,可以存储简单的键值对数据。它非常适合存储用户设置、用户偏好和其他应用程序数据,包括登录信息。SharedPreferences具有以下优点:轻量级:Shared......
  • 如何获取 Android 设备的CPU核数、时钟频率以及内存大小
    DeviceYearClass的主要功能是根据CPU核数、时钟频率以及内存大小对设备进行分级。下表是Facebook公司提供的分级标准,其中Year栏表示分级结果。以下类就是从Facebook的开源项目DeviceYearClass中拿出来的packagecom.yirui.youbao.util;importandroid.annotati......
  • 今日总结 Android与硬件设备通信(一)
    今天看了看Android与硬件通信的原理1、建立连接的原理在实现软件与硬件交互的时候,首先需要了解该硬件的构造,运行流程等相关操作,熟读相关的文档,知道硬件开发商那边给出了哪些接口,分别对应我们项目中的那些模块等等就拿我这个项目的硬件来说,供应商给出的连接流程如下图:  我......
  • Android中asset文件夹和raw文件夹区别
    res/raw和assets的相同点:1.两者目录下的文件在打包后会原封不动的保存在apk包中,不会被编译成二进制。res/raw和assets的不同点:1.res/raw中的文件会被映射到R.java文件中,访问的时候直接使用资源ID即R.id.filename;assets文件夹下的文件不会被映射到R.java......
  • Android service的完全详解
    Service全部内容基本会在本篇涉及到,我们将围绕以下主要知识点进行分析:Service简单概述Service在清单文件中的声明Service启动服务实现方式及其详解Service绑定服务的三种实现方式关于启动服务与绑定服务间的转换问题前台服务以及通知发送服务Service与线程Thread的区别管理......
  • 可左右两侧挤压傍边布局的Android抽屉
    我参考了这篇文章,我将它改了一下:可动态布局的Android抽屉之基础工程中需要这样的效果,左边和右边的Panel可以打开关闭:我把左边和右边的Panel封装成2个类了。这里要特别注意,抽屉是需要“handler”的,我这里可以把任何View都看成“handler”,使用setBindView(Vie......
  • Android自定义捕获Application全局异常
    参考:http://bigcat.easymorse.com/?p=1152packageqianlong.qlmobile.ui;importjava.io.File;importjava.io.FileOutputStream;importjava.io.FilenameFilter;importjava.io.PrintWriter;importjava.io.StringWriter;importjava.io.Writer......