The dimensions that are assigned to the view, when declared with match_parent
or wrap_content
, are calculated only at the time they are presented(Measurement phase), this is only done after the method onCreate()
be executed.
One way around this is to declare a listener 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);
}
});
}
Where do you want to use this code? No
onCreate()
of Activity?– ramaral
yes. I call the method I use this code in onCreate.
– daniel12345smith