Java tutorial
//package com.java2s; //License from project: Apache License import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.ViewTreeObserver.OnGlobalLayoutListener; public class Main { @SuppressLint("NewApi") public static void setViewDimens(Context context, final ViewGroup parent, final View view, final int width, final int height) { parent.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @SuppressWarnings("deprecation") @Override public void onGlobalLayout() { LayoutParams params = view.getLayoutParams(); if (params == null) { params = new LayoutParams(width, height); view.setLayoutParams(params); } else { params.width = width; params.height = height; } // remove OnGlobalLayoutListener, check Android version // too if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) parent.getViewTreeObserver().removeOnGlobalLayoutListener(this); else parent.getViewTreeObserver().removeGlobalOnLayoutListener(this); } }); } }