【问题标题】:Differences between: myView.getLayoutParams().height = screenHeight and myView.setLayoutParams(lp)?之间的区别:myView.getLayoutParams().height = screenHeight 和 myView.setLayoutParams(lp)?
【发布时间】:2015-10-24 13:14:18
【问题描述】:

当涉及到动态更改布局的高度时,我通常使用 LayoutParams 设置所需的尺寸,例如:

RelativeLayout myView = (RelativeLayout) v.findViewById(R.id.myView);     
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.FILL_PARENT,
                        screenHeight);

    myView.setLayoutParams(lp);

但也有这个较短的版本:

myView.getLayoutParams().height = screenHeight;

两者都适用于我的情况,我当然更喜欢第二个版本,因为它更简单,但是我需要注意两者之间有什么区别吗?

谢谢!

【问题讨论】:

    标签: android dynamic height android-relativelayout layoutparams


    【解决方案1】:

    你可以看看source code的View。

    当调用setLayoutParams时,也会执行以下语句。

    resolveLayoutParams();
    if (mParent instanceof ViewGroup) {
        ((ViewGroup) mParent).onSetLayoutParams(this, params);
    }
    requestLayout();
    

    所以基本上requestLayout() 会立即被调用。家长也会被告知这些变化。

    当使用myView.getLayoutParams().height = screenHeight; 时,视图也必须重新布局。这可能由视图本身在其他点完成,或者必须手动完成。

    这取决于你调用 myView.getLayoutParams().height = screenHeight;的时间

    如果在第一次布局/测量视图之前调用getLayoutParams().height = screenHeight;,这应该可以工作。

    【讨论】:

    • 嗯,很有趣。好吧,这似乎是以编程方式更改尺寸时的重要一点。也许这可能是我们使用 setLayoutParams 时覆盖 xml 参数的原因(它发生在我身上)。
    猜你喜欢
    • 2016-04-13
    • 2018-01-13
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 2021-12-25
    • 2020-05-10
    • 2014-09-20
    • 2010-10-28
    相关资源
    最近更新 更多