1、textview跟随button移动
效果图:
代码:
mainactivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn).setOnTouchListener(new View.OnTouchListener() {
@Override public boolean onTouch(View v, MotionEvent event) {// 按钮滑动事件
switch (event.getAction()){
case MotionEvent.ACTION_MOVE:
Log.d("移动:","1"+event.getRawX()+"/"+event.getRawY());
v.setX(event.getRawX()-v.getWidth()/2);
v.setY(event.getRawY()-v.getHeight()/2);
break;
}
return false;
}
});
}
}
EasyBehavior
public class EasyBehavior extends CoordinatorLayout.Behavior<TextView> {//这里的泛型是child的类型,也就是观察者View
public EasyBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, TextView child, View dependency) {
//告知监听的dependency是Button
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);
child.setText(dependency.getX()+","+dependency.getY());
return true;
}
}
xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<TextView
app:layout_behavior=".EasyBehavior"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="观察者View child"
/>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="被观察View dependency"
/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>