`

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

阅读更多
来自老外:
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();
    }
    
    
}



  • 大小: 11.6 KB
分享到:
评论
5 楼 xinyuetonghua 2012-05-03  
请教下,怎么解决同一个按钮的OnTouchListener()事件和onclick事件的冲突问题?
4 楼 songyu719 2011-10-22  
这个必须使用绝对布局吧!
3 楼 yelwen000 2011-06-21  
是不是只有button 能移动 的啊
Layout移动就不行了[e01]
[b][/b][color=red][/color]
2 楼 yelwen000 2011-06-21  
是不是只有button 能移动 的啊
Layout移动就不行了[e01]
1 楼 tanghanlin 2011-04-03  
怎么没效果

相关推荐

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

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

    android拖动图片拖动浮动按钮[归纳].pdf

    android拖动图片拖动浮动按钮[归纳].pdf

    Android自定义可拖拽的悬浮按钮DragFloatingActionButton

    主要介绍了Android自定义可拖拽的悬浮按钮DragFloatingActionButton,需要的朋友可以参考下

    Android 桌面漂浮按钮

    Android 桌面漂浮按钮 直接拖动

    Flutter任意拖动的悬浮按钮

    Flutter任意拖动的悬浮按钮,可以更改参数设定边界范围, 内包含多个Demo 仓库地址 https://github.com/ihongka/FlutterDIY

    FloatingActionButtonMenuDrag:带有菜单和可拖动控件的浮动操作按钮

    带有菜单和可拖动控件的浮动操作按钮 [ ]( ) 将其添加到存储库末尾的root build.gradle中: allprojects { repositories { ... maven { url 'https://jitpack.io' } } } 步骤2.添加依赖项 dependencies {...

    Android代码-自定义Floatview实现全站浮动按钮和来电秀

    自定义floatview,无需申明悬浮框权限,利用WindowManager TYPE_TOAST实现全站浮动式按钮,重写touch事件实现任意拖动,将view加入windowmanager层,可以使用控件实现类似来电秀的效果。 MIUI使用TYPE_TOAST也会无效...

    Android代码-SuspendButtonLayout

    一个带浮动按钮的布局,按钮可以展开 一.简介 一个轻量的带浮动按钮的布局。按钮可以随意展开关闭、显示隐藏,可以监听按钮打开、关闭、移动等状态,可以监听各个按钮的点击事件。无论你怎么拖动按钮,按钮最终都会...

    一个带浮动按钮的布局

    作者laocaixw,源码SuspendButtonLayout,一个轻量的带浮动按钮的布局。按钮可以随意展开关闭、显示隐藏,可以监听按钮打开、关闭、移动等状态,可以监听各个按钮的点击事件。无论你怎么拖动按钮,按钮最终都会停留...

    android-mouse-cursor:在 Android 中使用 AccessibilityService 模拟鼠标(无需 root)

    一个(某种功能的)示例,说明如何使用浮动窗口和可访问性服务在 Android 上模拟鼠标以单击视图。 用法 在 Android Studio 中打开项目并在您的设备上运行。 前往“设置”&gt;“辅助功能”并打开“鼠标光标”。 将...

    react-native-floatWindow:RN仿微信悬浮窗口

    将SuspensionWindow浮动块拖动到自己的浮动块上 第三步 import React , { Component } from 'react' import { StyleSheet , Text , View , TouchableOpacity } from 'react-native' import SuspendScreen from '...

    AnyLayer:Android稳定高效的浮层创建管理框架

    简介同时兼容support和androidx链式调用支持自由扩展实现几种常用效果Dialog/BottomSheet效果占用区域不会超过当前Activity避免导航栏遮挡支持自定义大小和显示位置支持自定义数据绑定支持自定义进出场动画支持...

    AutoClicker:使用Android Studio辅助功能制作的自动答题器应用

    自动点击器 使用android studio辅助功能制作的自动答题器应用程序在可拖动的浮动窗口上按下“开始”按钮后,该应用程序将代表用户在浮动窗口的当前位置“点击”屏幕

    OmniList:开源的时间管理应用程序,基于Material Design设计

    【浮动按钮】除了快捷方式,多功能清单还允许您使用浮动按钮快速创建任务,你还可以自定义自己的浮动按钮; 【日历】日历当然是不能少的,我们为你准备了一个按月方式展示的日历,它还支持公历农历和日历等; ...

    AndroidLAnimations:使用 RecyclerView 编译 Material Design 和动画

    AndroidL动画 使用 RecyclerView 编译 Material Design 和动画 ... vii) 使用浮动按钮库添加行 viii) 在触摸按钮或可操作文本时使用涟漪动画库制作涟漪 xi) 使用 Reachability 库实现 Reachability 功能(来自

    PonyTown Plugin-crx插件

    命令按钮(全屏和F4,认为是移动设备)-移动按钮-移动按钮的比例,不透明度和位置-表情符号编辑模式,能够编辑表情符号本身,其快捷方式以及可以发送的方法-使用JSON导出和导入表情符号-所有设置之间的浮动注释...

    无需申明悬浮框权限效果

    作者AlexLiuSheng,源码FloatView,自定义floatview,无需申明悬浮框权限,利用WindowManager TYPE_TOAST实现全站浮动式按钮,重写touch事件实现任意拖动,将view加入windowmanager层,可以使用控件实现 类似来电秀的...

    JAVA上百实例源码以及开源项目

    此时此景,笔者只专注Android、Iphone等移动平台开发,看着这些源码心中有万分感慨,写此文章纪念那时那景! Java 源码包 Applet钢琴模拟程序java源码 2个目标文件,提供基本的音乐编辑功能。编辑音乐软件的朋友,这...

    JAVA上百实例源码以及开源项目源代码

    Java数组倒置 简单 Java图片加水印,支持旋转和透明度设置 摘要:Java源码,文件操作,图片水印 util实现Java图片水印添加功能,有添加图片水印和文字水印,可以设置水印位置,透明度、设置对线段锯齿状边缘处理、水印...

Global site tag (gtag.js) - Google Analytics