jueves, 18 de julio de 2013

How to get view dimensions at onCreate

Hi, Trying to get the dimensions of my RelativeLayout at the onCreate of my Activity without no success, at the begining teh code seemed very easy :
RelativeLayout dashboard = (RelativeLayout)findViewById(R.id.dashboard);
int width = dashboard.getWidth()
no luck!, in this case getWidth() is always 0. Then I tryed to figure out why this happens and I realize that dashboard is not rendered yet, so, I have to find a callback after rendering to get the dashboard width... no luck! onResume didn't work neither, so I was researching through internet and I've found this blog where my problem is perfect solved. I've just going to put the code but you can read the entire article at http://code2thought.blogspot.com.es/2011/01/getting-layout-dimensions-in-android.html
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.dashboard);
  
  RelativeLayout dashboard = (GridLayout)findViewById(R.id.dashboard);
  
  
  dashboard.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
   
   @Override
   public void onGlobalLayout() {
    
    int width = dashboard.getWidth()
    
   }
  });
  
 }
happy coding!

No hay comentarios:

Publicar un comentario