How to find the Width of the a view before the view is displayed?

前端 未结 6 548
耶瑟儿~
耶瑟儿~ 2020-12-14 01:07

How to find the Width of the a view before the view is displayed? I do not want to add a custom view and tap the dimensions in the OnChanged().

相关标签:
6条回答
  • 2020-12-14 01:10

    This is the best way...... WORK!!!

    public void onWindowFocusChanged(boolean hasFocus) {          
      super.onWindowFocusChanged(hasFocus);
    
      if (fondo_iconos_height==0) { // to ensure that this does not happen more than once
          fondo_iconos.getLocationOnScreen(loc);
          fondo_iconos_height = fondo_iconos.getHeight();
          redraw_function();
      }
    
     }
    
    0 讨论(0)
  • 2020-12-14 01:14

    I like to use this technique as per my answer on a related question:

    Post a runnable from onCreate() that will be executed when the view has been created:

        contentView = findViewById(android.R.id.content);
        contentView.post(new Runnable()
        {
            public void run()
            {
                contentHeight = contentView.getHeight();
            }
        });
    

    This code will run on the main UI thread, after onCreate() has finished.

    0 讨论(0)
  • 2020-12-14 01:19
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    view.measure(size.x, size.y);
    int width = view.getMeasuredWidth();
    int height = view.getMeasuredHeight();
    
    0 讨论(0)
  • 2020-12-14 01:20
    Display display = getWindowManager().getDefaultDisplay();
    View view = findViewById(R.id.YOUR_VIEW_ID);
    view.measure(display.getWidth(), display.getHeight());
    
    view.getMeasuredWidth(); // view width
    view.getMeasuredHeight(); //view height
    
    0 讨论(0)
  • 2020-12-14 01:30

    @dmytrodanylyk -- I think it will return width & height as 0 so you need to use following thing

    LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View contentview = inflater.inflate(R.layout.YOURLAYOUTNAME, null, false);
    contentview.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
    int width = contentview.getMeasuredWidth();
    int height = contentview.getMeasuredHeight();
    

    It will give you right height & width.

    0 讨论(0)
  • 2020-12-14 01:30

    You should use OnGlobalLayoutListener which is called for changes on the view, but before it is drawn.

    costumView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    
        @Override
        public void onGlobalLayout() {
    
          costumView.getWidth();
    
        }
    });
    
    0 讨论(0)
提交回复
热议问题