Snippet to determine a size of control in Android

No comments on Snippet to determine a size of control in Android

Written by

in

It is a common task to get a control size. You may need it to create image assets to customize that control.

First we get a control object, for example ToggleButton. Then we get a pixel density of the device. After that we can convert px units to dp units.

ToggleButton toggleButton = (ToggleButton) getView().findViewById(R.id.toggleHideFromAgency);
float density = getActivity().getResources().getDisplayMetrics().density;
float width = toggleButton.getWidth();
float height = toggleButton.getHeight();
//float px = someDpValue * density;
float dpWidth = width / density;
float dpHeight = height / density;
Log.v(Helper.TAG, "ToggleButton width = " + Float.toString(dpWidth));
Log.v(Helper.TAG, "ToggleButton height = " + Float.toString(dpHeight));

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *