How to know what "MATCH_PARENT" will look like when the view is drawn?

Asked

Viewed 174 times

2

I’m using this code:

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

The second paramentric, the LayoutParams.MATCH_PARENT which represents the height is the size of a horizontal layout I created. In the first parameter I put 40 to be exactly one square (I’m using this in a button).

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

  • Where do you want to use this code? No onCreate() of Activity?

  • yes. I call the method I use this code in onCreate.

1 answer

4


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);
            }
        });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.