Activity中获取view的宽高

方式一:

view.post(new Runnable()
{
   @Override
   public void run()
   {
      Log.d("ssss","Width = "+view.getWidth());
      Log.d("ssss","Height = "+view.getHeight());
   }
});

输出:
 Width = 308
  Height = 168

view 在执行完onMeasure()后会调用 post()
方式二:
 
  
Observer方法
view.getViewTreeObserver().addOnGlobalLayoutListener( new OnGlobalLayoutListener() {
  @Override   public void onGlobalLayout() {      // 宽高已经测量完毕      
      Log.d("ssss","Width = "+view.getWidth());
      Log.d("ssss","Height = "+view.getHeight());
view.getViewTreeObserver().removeGlobalOnLayoutListener( this) ;
   }
  }
);

方式三

@Override
public void onWindowFocusChanged(boolean hasFocus)
{
   super.onWindowFocusChanged(hasFocus);

   view.getHeight();
   Log.d("ssss","hight = "+view.getHeight());
   Log.d("ssss","Width = "+view.getWidth());
}方式四:
 
  
view.setOnClickListener(new

OnClickListener()
{

   @Override public void onClick (View v){
   
Log.d("ssss","hight = "+view.getHeight());
   Log.d("ssss","Width = "+view.getWidth());
}
  }
);




你可能感兴趣的:(android)