跟谁手指移动的一个View
布局文件:
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="观察者View child" android:textColor="#333333" app:layout_behavior="com.czb.test.behavior.FollowBehavior" /> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="被观察View dependency(依赖者)" /> </android.support.design.widget.CoordinatorLayout>
Behavior的自定义
package com.czb.test.behavior; import android.content.Context; import android.support.design.widget.CoordinatorLayout; import android.util.AttributeSet; import android.view.View; import android.widget.Button; import android.widget.TextView; /** * Created by czb365 on 2018/3/19. */ public class FollowBehavior extends CoordinatorLayout.Behavior<TextView> {//这里的泛型是child的类型,也就是观察者View //这个构造方法比写 public FollowBehavior(Context context, AttributeSet attrs) { super(context, attrs); } @Over ride//关心那个View,也就是被观察者,也称依赖者 public boolean layoutDependsOn(CoordinatorLayout parent, TextView child, View dependency) { return dependency instanceof Button; } @Override//当 dependency(Button)变化的时候,可以对child(TextView)进行操作 public boolean onDependentViewChanged(CoordinatorLayout parent, TextView child, View dependency) { child.setX(dependency.getX() + 200); child.setY(dependency.getY() + 200); return true; } }
activity代码
@Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_move_view); findViewById(R.id.btn).setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_MOVE: v.setX(event.getRawX() - v.getWidth() / 2); v.setY(event.getRawY() - v.getHeight() / 2); break; } return false; } }); }