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。


  • 相关阅读:
    webyestem(伊莱博)票据管理(ver1.0)数据库设计
    MicrosoftNorthwind(电子商务)数据库设计
    WebForm三层架构
    WebForm带接口工厂模式的三层架构
    VS 2008 C#代码调试进C++代码设置/远程调试
    C# 中使用指针
    互操作性——使用C/C++类型的非托管函数基础
    Perforce使用指南_forP4V
    [转]DotNet程序之找BUG心得
    C# 对XML基本操作总结
  • 原文地址:https://www.cnblogs.com/qhyuan1992/p/5385342.html
Copyright © 2011-2022 走看看