Meysam Valiolahi
Meysam Valiolahi

Reputation: 188

in android how can i get view height or width?

i want to get my image view height and width at run time, when i use img1.getWidth() return zero ...

i search but suggest solutions are not work for me.. can anybody help me?

below code dos not work for me , in fact returned number is incorrect

    img1.post(new Runnable()
    {
        public void run()
        {
            int c = img1.getHeight();
            Toast.makeText(getApplicationContext(), c + "", Toast.LENGTH_LONG).show();

        }
    });

Upvotes: 0

Views: 1212

Answers (2)

Phuc Tran
Phuc Tran

Reputation: 8073

Try img1.getLayoutParams().width and img1.getLayoutParams().height

If it's not working, try below

img1.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int width = img1.getMeasuredWidth();
int height = img1.getMeasuredHeight();

Upvotes: 3

Darryl Bayliss
Darryl Bayliss

Reputation: 2712

Looking at the API documentation, this method should be what you need. You force the view to measure itself in runtime so you know exactly what dimensions the view is at that moment, it maybe an entirely different size on a different size screen.

Then you just call getMeasuredWidth() or getMeasuredHeight()

Used in an example:

img1.measure(MeasureSpec.EXACTLY, MeasureSpec.EXACTLY);
int width = img1.getMeasuredWidth();
int height = img1.getMeasuredHeight();

A quick caveat, the measure() method is available in every version of Android however the getMeasuredWidth() and getMeasuredHeight() methods are only available in Android 4.1 and above.

Hope this helps

Upvotes: 1

Related Questions