简体   繁体   中英

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

I'd like to do something like the following:

rootLayout.getLayoutParams().height = 100;

Currently I have this line in my 'loadData' method. The problem is - 'layoutParams' seems to be null until sometime after 'loadData' has been called (but before it is displayed obviously).

Is there somewhere I can place this line where the layoutParams will have been instantiated, but still be before the view is shown for the first time?

    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();
            }
        });

You should consider to set layoutParams of this view as

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

So You can set layoutParams height as 100 and assuming that your parent view as linear layout ,if it's not, then you should use its layoutparams

on the docs you can check all the callbacks the view have that you can override https://developer.android.com/reference/android/view/View.html

if your view is inside an XML layout with the LayoutParams specified in there, you can/should put your code inside onFinishInflate

   @Override
   public void onFinishInflate() {
   }

if you're doing all this programmatically, you can override the layout pass

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

alternatively (a nicer approach in my opinion), you can trick the onMeasure of your view to have the size you want. For example, to have a view with a 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);
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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