How to know the value that "MATCH_PARENT" will have when the view is drawn?

1

I'm using this code:

LayoutParams par = new LayoutParams(40, LayoutParams.MATCH_PARENT);

The second paramentitro, LayoutParams.MATCH_PARENT representing the height is the size of a horizontal layout I created. In the first parameter I put 40 to get exactly one square (I'm using this on a button).

I needed to know how many pixels LayoutParams.MATCH_PARENT is using and apply the same to the first parameter, instead of this 40 so that my button would be square regardless of the resolution of the device that my app runs.

    
asked by anonymous 18.11.2015 / 14:23

1 answer

3

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);
            }
        });
}
    
19.11.2015 / 17:16