Basically my question is: how to move a complete view around, instead of just moving the canvas? *I have a custom view and I want to move the whole thing not just the canvas.*
This is what I have tried, but I get a NullPointerException (the code is not compleate, I have put what I think is the most relevant part, also the parent of the custom view is a LinearLayout):
ResistorView class:
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;
}
main layout:
<?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>
I don’t know what I am doing wrong, if someone can help I would really appreciated. Thanks.
Change
to
You may even want to do this inside of onTouch instead and remove it from the constructor, something like: