android 控件跟随手指移动

发布时间:2016-12-7 0:02:11 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"android 控件跟随手指移动",主要涉及到android 控件跟随手指移动方面的内容,对于android 控件跟随手指移动感兴趣的同学可以参考一下。

项目中遇到控件跟随手指触摸移动的部分,简单测试了下。 package com.example.viewanimationtest; /** * @author maria * 2013-2-16 */ import android.os.Bundle; import android.app.Activity; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.RelativeLayout; public class MainActivity extends Activity implements OnTouchListener { Button _view; ViewGroup _root; private int _xDelta; private int _yDelta; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); _root = (ViewGroup) findViewById(R.id.root); _view = (Button) findViewById(R.id.id_text); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( 150, 50); layoutParams.leftMargin = 50; layoutParams.topMargin = 50; layoutParams.bottomMargin = -250; layoutParams.rightMargin = -250; _view.setLayoutParams(layoutParams); _view.setOnTouchListener(this); } public boolean onTouch(View view, MotionEvent event) { final int X = (int) event.getRawX(); final int Y = (int) event.getRawY(); switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view .getLayoutParams(); _xDelta = X - lParams.leftMargin; _yDelta = Y - lParams.topMargin; break; case MotionEvent.ACTION_UP: break; case MotionEvent.ACTION_POINTER_DOWN: break; case MotionEvent.ACTION_POINTER_UP: break; case MotionEvent.ACTION_MOVE: RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view .getLayoutParams(); layoutParams.leftMargin = X - _xDelta; layoutParams.topMargin = Y - _yDelta; layoutParams.rightMargin = -250; layoutParams.bottomMargin = -250; view.setLayoutParams(layoutParams); break; } _root.invalidate(); return true; } } <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/root" tools:context=".MainActivity" > <Button android:id="@+id/id_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/hello_world" /> </RelativeLayout>

上一篇:2.1 数据块,数据扩展,段简介
下一篇:Python性能分析指南

相关文章

相关评论