您当前的位置: 首页 >  android

Kevin-Dev

暂无认证

  • 0浏览

    0关注

    544博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Android -- Material Design】CoordinatorLayout 的基本使用

Kevin-Dev 发布时间:2020-08-02 23:14:34 ,浏览量:0

前言

CoordinatorLayout 继承于ViewGroup,它就是一个超级强大 Framelayout。CoordinatorLayout 的作用就是协调子 View。

使用场景:

  1. 作为 一个应用顶层的装饰布局,也就是一个Activity Layout 的最外一层布局。
  2. As a container for a specific interaction with one or more child views,作为一个或多个有特定响应动作的容器。
效果图

在这里插入图片描述 解释一下这个动画,蓝色的矩形是我们一个普通 View,黄色的 Hello 是一个 Button。我们水平拖动蓝色矩形时,黄色 Button 查着与蓝色矩形相反方向移动;竖直移动蓝色矩形时,黄色也跟着竖直。

简而言之:它们在竖直方向同步移动,在水平方向相反。

代码实现

1. 定义一个类,继承 CoordinatorLayout.Behavior

/**
* 判断child的布局是否依赖dependency
*/
   @Override
 public boolean layoutDependsOn(CoordinatorLayout parent, T child, View dependency) {
    boolean rs;
    //根据逻辑判断rs的取值
    //返回false表示child不依赖dependency,ture表示依赖
    return rs;  
}

/**
* 当dependency发生改变时(位置、宽高等),执行这个函数
* 返回true表示child的位置或者是宽高要发生改变,否则就返回false
*/
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, T child, View dependency) {
     //child要执行的具体动作
        return true;
}

2. 实例代码

public class MyBehavior extends CoordinatorLayout.Behavior {
    private int width;

    public MyBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
        DisplayMetrics display = context.getResources().getDisplayMetrics();
        width = display.widthPixels;
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, Button child, View dependency) {
        //如果dependency是TempView的实例,说明它就是我们所需要的Dependency
        return dependency instanceof TempView;
    }

    //每次dependency位置发生变化,都会执行onDependentViewChanged方法
    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, Button btn, View dependency) {

        //根据dependency的位置,设置Button的位置

        int top = dependency.getTop();
        int left = dependency.getLeft();

        int x = width - left - btn.getWidth();
        int y = top;

        setPosition(btn, x, y);
        return true;
    }

    private void setPosition(View v, int x, int y) {
        CoordinatorLayout.MarginLayoutParams layoutParams = (CoordinatorLayout.MarginLayoutParams) v.getLayoutParams();
        layoutParams.leftMargin = x;
        layoutParams.topMargin = y;
        v.setLayoutParams(layoutParams);
    }
}

3. 布局文件




    



关注
打赏
1658837700
查看更多评论
立即登录/注册

微信扫码登录

0.0382s