如何在显示视图之前找到视图的宽度?

时间:2011-11-20 10:25:56

标签: android

如何在显示视图之前找到视图的宽度?我不想添加自定义视图并点击OnChanged()中的尺寸。

7 个答案:

答案 0 :(得分:42)

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

答案 1 :(得分:29)

@dmytrodanylyk - 我认为它将返回宽度&高度为0所以你需要使用以下内容

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

它会给你正确的高度和宽度。

答案 2 :(得分:10)

您应该使用OnGlobalLayoutListener来调用视图,但在绘制之前进行更改。

costumView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {

      costumView.getWidth();

    }
});

答案 3 :(得分:9)

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

答案 4 :(得分:3)

我喜欢按照my answer on a related question使用此技术:

发布将在创建视图时执行的onCreate()的runnable:

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

此代码将在onCreate()完成后在主UI线程上运行。

答案 5 :(得分:0)

这是最好的方式......工作!!!

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

 }

答案 6 :(得分:0)

yourView.measure(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    int yourView= m_hidableRowContainer.getMeasuredHeight();

那就是它。