Android 如何移动自定义视图?
基本上我的问题是:如何移动一个完整的视图,而不是仅仅移动画布*我有一个自定义视图,我想移动整个东西,而不仅仅是画布* 这是我尝试过的,但是我得到了一个NullPointerException,代码不完整,我把我认为最相关的部分放进去了,而且自定义视图的父视图是一个LinearLayout: ResistorView类:Android 如何移动自定义视图?,android,android-layout,android-custom-view,Android,Android Layout,Android Custom View,基本上我的问题是:如何移动一个完整的视图,而不是仅仅移动画布*我有一个自定义视图,我想移动整个东西,而不仅仅是画布* 这是我尝试过的,但是我得到了一个NullPointerException,代码不完整,我把我认为最相关的部分放进去了,而且自定义视图的父视图是一个LinearLayout: ResistorView类: LinearLayout root; public class ResistorView extends View{ public ResistorView(Cont
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>
我不知道我做错了什么,如果有人能帮助我,我将不胜感激。谢谢 变化
root = (LinearLayout)findViewById(R.id.main);
到
您甚至可能希望在onTouch内部执行此操作,并将其从构造函数中删除,例如:
if(root == null) {
root = (LinearLayout)getParent();
}
root.invalidate();
我建议使用FrameLayout并调用myCustomView.setXx和myCustomView.setYy 传递给方法的x和y是事件rawX和rawY+deltaX和deltaY 行动计划
deltaX = v.x - event.rawX
deltaY = v.y - event.rawY
deltaX和deltaY是全局变量
在行动中,你可以这样做
v.x = event.rawX + deltaX
v.y = event.rawY + deltaY
您要在其中移动它吗?视图位于线性布局内,因此我想我应该将其移动到线性布局内。看起来父级是线性布局。我编辑以添加main.xml layout.BTW-这是活动内的类吗?如果是这样,请确保您正在调用ViewgetParent而不是ActivitygetParent。如果是,它也可能会解释其损坏的原因。您很可能在构造函数中调用ViewfindViewById而不是ActivityfindViewById。谢谢。这就解决了问题。令人惊讶的是,像这样的小事能带来巨大的变化。再次感谢。
v.x = event.rawX + deltaX
v.y = event.rawY + deltaY