【问题标题】:Why use "setLayoutParams" after "getLayoutParams"?为什么我们使用 setLayoutParams?
【发布时间】:2016-05-31 17:14:27
【问题描述】:

例如,如果您想以编程方式将 widthheight 的某些视图的 LayoutParams 更改为 WRAP_CONTENT,它将看起来像这样:

 final ViewGroup.LayoutParams lp = yourView.getLayoutParams();
 lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
 lp.width = ViewGroup.LayoutParams.WRAP_CONTENT;

由于我无法理解 getLayoutParams 返回参数的引用,所以这段代码就足够了,但我经常在示例等中看到,在这行之后,下面是:

 yourView.setLayoutParams(lp);

我想知道这条线的意义何在。这只是为了更好的代码可读性还是在某些情况下没有它就无法工作?

【问题讨论】:

  • 我投票可读性。不过,我从未见过这些必须动态调整现有视图大小的示例。我通常会看到视图被动态添加到内容视图中。在这些情况下,需要 setLayoutParams

标签: android layoutparams


【解决方案1】:

如果您不使用 setLayoutParams(),您的布局设置将在调用 View.onLayout() 时生效。

这里是View.setLayoutParams()的源码

public void setLayoutParams(ViewGroup.LayoutParams params) { if (params == null) { throw new NullPointerException("Layout parameters cannot be null"); } mLayoutParams = params; resolveLayoutParams(); if (mParent instanceof ViewGroup) { ((ViewGroup) mParent).onSetLayoutParams(this, params); } requestLayout(); }

如您所见,requestLayout 将在 setLayoutParams 中调用。此视图将立即重新布局。 onLayout 也会被调用。

【讨论】:

    【解决方案2】:

    setLayoutParams() 也会触发resolveLayoutParams()requestLayout(),它们会通知视图发生了变化,刷新它。或者我们无法确保新的布局参数真正起作用。


    View.setLayoutParams源代码:

    public void setLayoutParams(ViewGroup.LayoutParams params) {
        if (params == null) {
            throw new NullPointerException("Layout parameters cannot be null");
        }
        mLayoutParams = params;
        resolveLayoutParams();
        if (mParent instanceof ViewGroup) {
            ((ViewGroup) mParent).onSetLayoutParams(this, params);
        }
        requestLayout();
    }
    

    【讨论】:

    • 所以基本上我们只有在视图已经绘制好的情况下才需要它,然后我们需要更改它?
    • 是的。在运行时更改现有视图参数时调用它
    【解决方案3】:

    无法确保您对 getLayoutParams() 返回的 LayoutParams 所做的任何更改都会正确反映。它可以因Android版本而异。因此,您必须致电 setLayoutParams() 以确保视图会更新这些更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-11
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多