目标:一步一步掌握拖动控件等比较炫的效果,先从超级简单版学起==、
利用view.setOnTouchListener(...) ,view.setLayoutParams(...) ,leftMargin ,topMargin
view.layout(int left,int top,int right ,int bottom) ;
参考博客: http://blog.csdn.net/actual_/article/details/8582313
贴代码一:
public class MainActivity extends Activity implements OnTouchListener{
View _view;
ViewGroup _root;
private int _xDelta;
private int _yDelta;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE); 去Title
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
// WindowManager.LayoutParams.FLAG_FULLSCREEN); 去状态栏
setContentView(R.layout.activity_main);
_root = (ViewGroup) findViewById(R.id.root);
_view = (View) findViewById(R.id.id_view);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
200, 200);//为什么数值200还显得小,因为这里是px像素,而非dp
layoutParams.leftMargin = 50;//查看到源码:The left margin in pixels of the child.
layoutParams.topMargin = 50; //说明这里也是px
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.leftMargin = X; 这样是错误的,因为getRawX是物理屏幕为坐标
// layoutParams.topMargin = Y; 获取到的往往还可能有Title和状态栏
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
view.setLayoutParams(layoutParams);
//这种也可以 view.layout( X - _xDelta, Y - _yDelta, -250,-250);
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" >
<View
android:id="@+id/id_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/holo_green_dark" />
</RelativeLayout>
贴截图: