zoukankan      html  css  js  c++  java
  • getLayoutParams()和setLayoutParams()方法源码

    今天在写侧滑菜单的时候发现了这个一个问题,初始化的时候在onCreate函数里面设置menu的leftMargin:

    menulParams = (LayoutParams) menu.getLayoutParams();
    menulParams.width = menuWidth;
    menulParams.leftMargin = -1*menuWidth;
    content.getLayoutParams().width = screenWidth;
    无需调用setLayoutParams函数就可以实现效果,我的解释就是通过getLayoutParams函数得到了LayoutParams的引用,然后修改这个值肯定是会生效的,然而在触摸事件中,我也如法炮制,但是却始终划不出来。

    Log.i("debug", "show");
    //显示菜单
    menulParams.leftMargin = 0;

    为什么在onCreate中设置参数的时候get出来设置一下就可以,现在却不可以了呢?于是决定查看一下源代码是怎么回事:

       /**
         * Get the LayoutParams associated with this view. All views should have
         * layout parameters. These supply parameters to the <i>parent</i> of this
         * view specifying how it should be arranged. There are many subclasses of
         * ViewGroup.LayoutParams, and these correspond to the different subclasses
         * of ViewGroup that are responsible for arranging their children.
         * @return The LayoutParams associated with this view
         */
        @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
        public ViewGroup.LayoutParams getLayoutParams() {
            return mLayoutParams;
        }
    
        /**
         * Set the layout parameters associated with this view. These supply
         * parameters to the <i>parent</i> of this view specifying how it should be
         * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
         * correspond to the different subclasses of ViewGroup that are responsible
         * for arranging their children.
         *
         * @param params the layout parameters for this view
         */
        public void setLayoutParams(ViewGroup.LayoutParams params) {
            if (params == null) {
                throw new NullPointerException("params == null");
            }
            mLayoutParams = params;
            requestLayout();
        }
    可以看出:getLayoutParams就是将布局参数的引用返回来,在setLayoutParams函数中除了将布局的形参赋值,还有调用了requestLayout()

    恍然大悟,设置参数后是需要对View进行重绘的。在onCreate里面的代码执行的时候View还没有绘制,所以设置完参数后接下来绘制就会生效,而后来的布局参数的改变必须自己调用使View进行重新绘制,所以需要调用setLayoutParams函数!

    为了验证,我们不调用setLayoutParams函数,添加上同样OK。

    menu.requestLayout();
    同样OK。


  • 相关阅读:
    server 2016部署网络负载平衡(NLB)
    Windows Server 2012 搭建DHCP及远程路由访问
    第一章 Windows Server 2016网络管理
    不懂 ZooKeeper?没关系,这一篇给你讲的明明白白
    更新bios后进不了系统
    ICP备案和ICP许可证
    C# 解决“请求被中止: 未能创建 SSL/TLS 安全通道”的问题
    Is EnableViewStateMAC=true compulsory for ViewStateEncryption in an ASP.Net Website?
    Uses for MachineKey in ASP.NET
    5月底更新后桌面右下角出现的新闻资讯怎么删除?
  • 原文地址:https://www.cnblogs.com/qhyuan1992/p/5385342.html
Copyright © 2011-2022 走看看