如何使用onTouchListener使Textview在布局内可移动

时间:2019-05-07 09:22:27

标签: java android ontouchlistener

我正在创建一个可移动的textview。它按照我想要的方式移动。但问题在于它可以移出版面。
那么我该如何设置边界以限制textview在布局内移动。

我想将LinearLayout(@ id / moveTextViewInThisLayout)设置为边界。因此textview不应移出此线性布局

这是我的Java文件

public class TestFragment extends Fragment implements 
    View.OnTouchListener {

    float dx;
    float dy;
    int lastaction;
    LinearLayout linearLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.test, container, false);

        linearLayout = rootView.findViewById(R.id.moveTextViewInThisLayout);

        View dragView = rootView.findViewById(R.id.draggable_view);
        dragView.setOnTouchListener(TestFragment.this);

        return rootView;

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getActionMasked()){
            case MotionEvent.ACTION_DOWN:
                dx = v.getX() - event.getRawX();
                dy = v.getY() - event.getRawY();
                lastaction = MotionEvent.ACTION_DOWN;
                break;
            case MotionEvent.ACTION_MOVE:
                v.setY(event.getRawY() + dy);
                v.setX(event.getRawX() + dx);
                lastaction = MotionEvent.ACTION_MOVE;
                break;
            case MotionEvent.ACTION_UP:
                if(lastaction == MotionEvent.ACTION_DOWN){
                    Toast.makeText(getActivity(), "Clicked",
    Toast.LENGTH_LONG).show();
                }
                break;
            default:
                return false;
        }
        return true;
    }
}

这是我的布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_margin="10dp"
        android:id="@+id/moveTextViewInThisLayout">

        <RelativeLayout
            android:id="@+id/draggable_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/draggable_view1"
                android:textSize="30dp"
                android:text="Hello"
                android:layout_marginTop="20dp"
                android:layout_marginLeft="20dp"/>

        </RelativeLayout>

    </LinearLayout>



</LinearLayout>

0 个答案:

没有答案