Dimensions that are assigned to view , when declared with match_parent
or wrap_content
, are only calculated when they are displayed ( measurement phase ) , this is only done after the onCreate()
method is executed.
One of the ways to circumvent this situation is to declare a listenner which is called after this calculation.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
....
final View aSuaView = findViewById(R.id.aSuaView);
aSuaView.getViewTreeObserver().addOnGlobalLayoutListener(new
ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//Remove o listenner para não ser novamente chamado.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
aSuaView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
//noinspection deprecation
aSuaView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
//Coloca a largura igual à altura
ViewGroup.LayoutParams layoutParams =
(LinearLayout.LayoutParams) aSuaView.getLayoutParams();
layoutParams.width = layoutParams.height();
aSuaView.setLayoutParams(layoutParams);
}
});
}