今天在写侧滑菜单的时候发现了这个一个问题,初始化的时候在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。