繁体   English   中英

Android:可以在绘制视图之前更改视图的高度吗?

[英]Android: Can I change the height of a view before it's drawn?

我想做以下事情:

rootLayout.getLayoutParams().height = 100;

目前,我的“ loadData”方法中包含此行。 问题是-“ layoutParams”似乎为空,直到调用了“ loadData”之后的某个时间(但是在明显显示之前)。

有什么地方可以放置此行的位置,该行将实例化layoutParams,但仍在第一次显示视图之前?

    rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    rootLayout.getViewTreeObserver()
                            .removeOnGlobalLayoutListener(this);
                } else {
                    rootLayout.getViewTreeObserver()
                            .removeGlobalOnLayoutListener(this);
                }
                rootLayout.getLayoutParams().height = 100;
                rootLayout.requestLayout();
            }
        });

您应该考虑将此视图的layoutParams设置为

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 100));
 rootLayout.setLayoutParams(lp);

因此,您可以将layoutParams的高度设置为100,并假设您的父视图为linear layout ,否则请使用其layoutparams

在文档上,您可以检查视图中所有的回调,您可以覆盖https://developer.android.com/reference/android/view/View.html

如果您的视图位于其中指定了LayoutParams的XML布局内,则可以/应该将代码放在onFinishInflate中

   @Override
   public void onFinishInflate() {
   }

如果您以编程方式执行所有操作,则可以覆盖版式传递

@Override
public void onLayout (boolean changed, int left, int top, int right, int bottom){
    // be carefull that this get's called several times
}

或者(我认为这是一种更好的方法),您可以欺骗视图的onMeasure使其具有所需的大小。 例如,要使视图具有maxWidth

   @Override
   protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
      // apply max width
      int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
      if (maxWidth > 0 && maxWidth < measuredWidth) {
         int measureMode = MeasureSpec.getMode(widthMeasureSpec);
         widthMeasureSpec = MeasureSpec.makeMeasureSpec(maxWidth, measureMode);
      }
      super.onMeasure(widthMeasureSpec, heightMeasureSpec);
   }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM