我正在尝试在Android应用程序的屏幕上四处移动textview。但是在将textview拖动到最终位置后,它随机移动到其他相对位置。
private final class TextViewTouchListener implements View.OnTouchListener {
@Override
public boolean onTouch(View view, MotionEvent event) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
//start dragging the item touched
view.startDrag(data, shadowBuilder, view, 0);
return true;
}
}
private final class TextViewDragListener implements View.OnDragListener {
@Override
public boolean onDrag(View v, DragEvent event) {
final float x = event.getX();
final float y =event.getY();
// handling the case when the textview gets dragged out of screen
leftMargin = Math.min(x, mDisplaySize.x - textview.getWidth());
topargin = Math.min(y, mDisplaySize.y - textview.getHeight());
final FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) textView.getLayoutParams();
params.leftMargin = (int) leftMargin;
params.topMargin = (int) topargin;
params.rightMargin = 0;
params.bottomMargin = 0;
textView.setLayoutParams(params);
return true;
}
}
Seems like I am handling it wrong. Can someone help me what exactly I am doing wrong.
答案 0 :(得分:0)
如果只想在屏幕上移动视图,则无需使用拖放;您只可以使用MotionEvent.ACTION_DOWN
的{{1}}和MotionEvent.ACTION_MOVE
事件来更新屏幕上视图的x和y位置。
为避免将视图移出屏幕,我们将使用其View.OnTouchListener
因此,您的布局将具有一个包含getViewTreeObserver()
的根视图,您想在屏幕上四处移动。
TextView
您的行为将是:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World" />
</RelativeLayout>
结果