Get height and width of a layout programmatically
The view itself, has it's own life cycle which is basically as follows:
Attached
Measured
Layout
Draw
So, depending on when are you trying to get the width/height you might not see what you expect to see, for example, if you are doing it during onCreate, the view might not even been measured by that time, on the other hand if you do so during onClick method of a button, chances are that by far that view has been attached, measured, layout, and drawn, so, you will see the expected value, you should implement a ViewTreeObserver to make sure you are getting the values at the proper moment.
LinearLayout layout = (LinearLayout)findViewById(R.id.YOUR VIEW ID);
ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
this.layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
int width = layout.getMeasuredWidth();
int height = layout.getMeasuredHeight();
}
});
How to get programmatically width and height of Relative - Linear layout in android?
Well I have implemented by this way:
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.layout);
ViewTreeObserver viewTreeObserver = linearLayout.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
linearLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = linearLayout.getMeasuredWidth();
int height = linearLayout.getMeasuredHeight();
}
});
This example is for Linear layout, for Relative layout follow same process.
Hope this would help you.
Android Get height of the visible layout programmatically
Sorry for Disturb , I solved my question for getting some ideas through other answer but i see some deprecated method which is suggested to solve it.
for actionbar And tabbar height
int tabHeight = mTabHost.getTabWidget().getHeight();
int actionbarheight = getSupportActionBar().getHeight();//getActionbar() insted of for Api greater 13 than
height of statusbar
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
int statusbarheight = getStatusBarHeight();
for getting screen size
Display display = getWindowManager().getDefaultDisplay();
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR2)
{
width = display.getWidth(); // deprecated
height = display.getHeight()- (tabHeight + actionbarheight + statusbarheight );
}
else {
Point size1 = new Point();
display.getSize(size1);
width = size1.x;
height = size1.y - (tabHeight + actionbarheight + statusbarheight);//visible layout height
}
View's getWidth() and getHeight() returns 0
You are calling getWidth()
too early. The UI has not been sized and laid out on the screen yet.
I doubt you want to be doing what you are doing, anyway -- widgets being animated do not change their clickable areas, and so the button will still respond to clicks in the original orientation regardless of how it has rotated.
That being said, you can use a dimension resource to define the button size, then reference that dimension resource from your layout file and your source code, to avoid this problem.
Get height of view programmatically when it is set to Wrap_content
Just give like
viewObj.getHeight():
Instead of this
layout.getLayoutParams().height
It will be work
Finding the Value of a Layout's Height and Width
when onCreate
is executed in your Activity
, the UI
has not been drawn to the screen yet, so nothing has dimensions yet since they haven't been laid out on the screen.
When setContentView
is called, a message is posted to the UI
thread to draw the UI
for your layout, but will happen in the future after onCreate finishes executing.
Posting a Runnable
to the UI
thread will put the Runnable
at the end of the message queue for the UI
thread, so will be executed after the screen has been drawn,thus everything has dimensions. (that's why you got a NullPointerException from Niza Siwale
answer)
btn.post(new Runnable() {
@Override
public void run() {
TableLayout myTableLayout = findViewById(R.id.idOfTheTableLayout);
int width = myTableLayout.getWidth();
int height = myTableLaout.getHeight();
ViewGroup.LayoutParams params = btn.getLayoutParams();
params.height = height;
params.width = width;
btn.setLayoutParams(params);
}
}
hope it works.
How to get correct height of Linear layout programmatically?
first of all you need a method to convert px to dp :
public float convertPixelsToDp(float px, Context context){
return px / ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}
then you can get height of your LinearLayout like this and show that in a Toast:
final LinearLayout layout = findViewById(R.id.container);
ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
int width = layout.getMeasuredWidth(); // this method return px value
int height = layout.getMeasuredHeight(); // this method return px value
Toast.makeText(MainActivity.this, "height is : " + convertPixelsToDp(height, MainActivity.this), Toast.LENGTH_LONG).show();
}
});
How can I set layout height and width programmatically which support all screen size in Android?
You can get the device density like this:
float scaledDensity = getResources().getDisplayMetrics().scaledDensity;
LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(20 * scaledDensity,20 * scaledDensity);
param1.weight=1;
How to get height of Layout, fiiled with elements programmatically
It takes some time for the linear layout to measure, pass to its children & correctly get its height. So you have to wait until its complete. Here is the code
TRIED IT & WORKING: JAVA CODE
linearLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int height = linearLayout.getMeasuredHeight();
if( Build.VERSION.SDK_INT > 15){
linearLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
linearLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
You set-up a listener for the layout, after getting the height, unregister the GlobalOnLayoutListener
You can either use linearLayout.getHeight()
or linearLayout.getMeasuredHeight()
. Both provided the same values in my test
XAMARIN CODE
ViewTreeObserver vto = _linearLayout.ViewTreeObserver;
vto.GlobalLayout += (sender, args) => {
var ht = linearLayout.Height;
};
How to get height in pixels of LinearLayout with layout_weight
try with ll.getHeight()
should work
if not, it's because android has not yet calculed its bounds, then:
//inside of onCreate method should work
ll.post(new Runnable() {
@Override
public void run() {
//maybe also works height = ll.getLayoutParams().height;
height = ll.getHeight();
}
});
Related Topics
How to Add Many Spaces After the Text in Textview
How to Turn a Portable Sd Card into Internal Storage Via Adb Command
Asking Camera Permission for Webview At Runtime
Fastest Way to Upload Multiple Image to Server in Android
Error "Gradle Sync Failed: Connection Refused: Connect"
Not Opening Specific Activity on Notification Click When the App Is in Background/Not Running
Change Button Background At Runtime in Android
Android Fastboot Devices Not Returning Device
Eclipse Compiles Successfully But Still Gives Semantic Errors
Html File Input in Android Webview (Android 4.4, Kitkat)
Html File Input Control With Capture and Accept Attributes Works Wrong
Chrome on Android Resizes Font
How to Open Whatsapp Using an Intent in Your Android App
What Is Install_Parse_Failed_No_Certificates Error
How to Format Credit Card Expiry Date in Mm/Yy When Entered by User