布局
<?xml version="1.0" encoding="utf-8"?><FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<View
android:id="@+id/view"
android:layout_width="32dp"
android:layout_height="32dp"
android:background="#909090" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="a\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\n"/>
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android=“http://schemas.android.com/apk/res/android”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
xmlns:app=“http://schemas.android.com/apk/res-auto”>
<!--
包裹内容
-->
<ImageView
android:layout_width="0dp"
android:layout_height="200dp"
android:background="#ff0000"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
public class MainActivity extends AppCompatActivity {
private View view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = findViewById(R.id.view);
view.setClickable(true);
view.setOnTouchListener(new View.OnTouchListener() {
private int downX, downY;
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {//按下
v.getParent().requestDisallowInterceptTouchEvent(true);
downX = (int) event.getX();
downY = (int) event.getY();
} else if(event.getAction() == MotionEvent.ACTION_MOVE) {
int currentX = (int) event.getX();
int currentY = (int) event.getY();
view.setTranslationX(view.getTranslationX() + currentX - downX);
view.setTranslationY(view.getTranslationY() + currentY - downY);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
}
return false;
}
});
}
}