以编程方式获取布局的高度和宽度

我设计了一个布局,其中 LinearLayout有2个孩子 LinearLayoutFrameLayout和在每个孩子我把不同的意见。

我只是想测量 FrameLayout的高度和宽度,这样我就可以为我的目的服务。

在我使用的程序中

int height,width;


FrameLayout fr=(FrameLayout)findviewbyid(R.id.fr);
height=fr.getHeight();
width=fr.getWidth();

返回值为 0

就连我也尝试过遵循代码 整数高度、宽度;

FrameLayout fr=(FrameLayout)findviewbyid(R.id.fr);
height=fr.getMeasuredHeight();
width=fr.getMeasuredWidth();

返回相同的值 0

最后我试着用下面的代码, 整数高度、宽度;

FrameLayout fr=(FrameLayout)findviewbyid(R.id.fr);
height=fr.getgetLayoutParams().height();
width=fr.getLayoutParams().width;

返回 -2-1

我想解决方案得到高度和宽度的任何布局编程?

136860 次浏览

The first snippet is correct, but you need to call it after onMeasure() gets executed. Otherwise the size is not yet measured for the view.

I think you are getting Height and Width in OnCreate() method that's why you getting always 0 values because at that time your view still not created.

Try to get height and width on some button click or else..

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


}
});

For frame:

height=fr.getHeight();
width=fr.getWidth();

For screen:

width = getWindowManager().getDefaultDisplay().getWidth();
height = getWindowManager().getDefaultDisplay().getHeight();

try something like this code from this link

ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
viewWidth = view.getWidth();
viewHeight = view.getHeight();
}
});
}

hope this helps.

I used DisplayMetrics to get the screen size and then i can assign the width/height to an element in %age

It will be like this

DisplayMetrics dmetrics = new DisplayMetrics();
int widthPixels=dmetrics.widthPixels;
int heightPixels=dmetrics.heightPixels;


//setting the height of the button
button_nextPuzzle.setMinHeight((int) ((heightPixels/3)*.30));

Worked for me very well!!!

If you get -1 or -2 it could also be the numeric value of LayoutParams.WRAP_CONTENT (-2) or LayoutParams.MATCH_PARENT (-1).

As CapDroid say, you are trying to get the size before the view drawn, another possible solution could be to do a Post with a runnable on the View:

mView.post(new Runnable() {
@Override
public void run() {
int width = mView.getWidth();
int height = mView.getHeight();
}
}

Most easiest way is to use ViewTreeObserver, if you directly use .height or .width you get values as 0, due to views are not have size until they draw on our screen. Following example will show how to use ViewTreeObserver

ViewTreeObserver viewTreeObserver = YOUR_VIEW_TO_MEASURE.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {


YOUR_VIEW_TO_MEASURE.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int viewHeight = YOUR_VIEW_TO_MEASURE.getHeight();
int viewWeight = YOUR_VIEW_TO_MEASURE.getWidth();


}
});
}

if you need to use this on method, use like this and to save the values you can use globle variables.

just give your height and You will get height or even width if wanted.

* Get the view height before the view will render * @param view the view to measure * @return the height of the view */

public static int getViewHeight(View view) {
WindowManager wm =
(WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();


int deviceWidth;


if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2){
Point size = new Point();
display.getSize(size);
deviceWidth = size.x;
} else {
deviceWidth = display.getWidth();
}


int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(deviceWidth, View.MeasureSpec.AT_MOST);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(widthMeasureSpec, heightMeasureSpec);
return view.getMeasuredHeight(); //        view.getMeasuredWidth();
}

I had same issue but didn't want to draw on screen before measuring so I used this method of measuring the view before trying to get the height and width.

Example of use:

layoutView(view);
int height = view.getHeight();


//...


void layoutView(View view) {
view.setDrawingCacheEnabled(true);
int wrapContentSpec =
MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
view.measure(wrapContentSpec, wrapContentSpec);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
}

try with this metods:

int width = mView.getMeasuredWidth();


int height = mView.getMeasuredHeight();

Or

int width = mTextView.getMeasuredWidth();


int height = mTextView.getMeasuredHeight();

In Kotlin you can simply do this:

fr.post {
height=fr.height
width=fr.width
}

As I just ran into this problem thought I would write it for kotlin,

my_view.viewTreeObserver.addOnGlobalLayoutListener {
// here your view is measured
// get height using my_view.height
// get width using my_view.width
}

or

my_view.post {
// here your view is measured
// get height using my_view.height
// get width using my_view.width
}

Just wanted to add an answer here, since Koltin has some convenience methods to do this, which are a lot less ugly than adding and removing a onGlobalLayoutListener:

view.doOnLayout {
it.measuredWidth
it.measuredHeight
}

You can see more of the convinience methods here.

you can use coroutines as well, like this one :

CoroutineScope(Dispatchers.Main).launch {
delay(10)
val width = view.width()
val height= view.height()
// do your job ....
}

Check behavior Very Simple Solution

  override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d(LOG, "MainActivity - onCreate() called")


fragments_frame.post {
Log.d(LOG, " fragments_frame.height:${fragments_frame.width}")
Log.d(LOG, " fragments_frame.height:${fragments_frame.measuredWidth}")
}
}

If you code in Kotlin use this nice extension function :

inline fun View.getDimensions(crossinline onDimensionsReady: (Int, Int) -> Unit) {
lateinit var layoutListener: ViewTreeObserver.OnGlobalLayoutListener
layoutListener = ViewTreeObserver.OnGlobalLayoutListener {
viewTreeObserver.removeOnGlobalLayoutListener(layoutListener)
onDimensionsReady(width, height)
}
viewTreeObserver.addOnGlobalLayoutListener(layoutListener)
}

Usage :

view.getDimensions { width, height ->
println("width = $width")
println("height = $height")
}

getDefaultDisplay().getHeight is deprecated. So better to use

getResources().getDisplayMetrics().heightPixels;