基本上我的问题是:如何移动一个完整view
的,而不是仅仅移动canvas
? *我有一个习惯view
,我想移动整个东西,而不仅仅是canvas
. *
这是我尝试过的,但我得到了一个NullPointerException
(代码不完整,我把我认为最相关的部分放在了,自定义的父级view
也是 a LinearLayout
):
电阻视图类:
LinearLayout root;
public class ResistorView extends View{
public ResistorView(Context context){
super(context);
root = (LinearLayout)findViewById(R.id.main);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
LinearLayout.LayoutParams lParams = (LinearLayout.LayoutParams) this.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:
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) this.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
this.setLayoutParams(layoutParams);
break;
}
root.invalidate(); //There is a NullPointerException on this line.
return true;
}
主要布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/main">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/bAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add RES" />
</LinearLayout>
我不知道我做错了什么,如果有人可以提供帮助,我将不胜感激。谢谢。