Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I try to get a FrameLayout's height in onGlobalLayout(), this piece of code is in the onCreate() method:
final FrameLayout layout = (FrameLayout)findViewById(R.id.detail_frame);
ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
layout.getViewTreeObserver().removeOnGlobalLayoutListener (this);
ViewGroup.LayoutParams lPF = layout.getLayoutParams();
int gg = layout.getHeight();
int hh = lPF.height;
The XML file:
<FrameLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/detail_frame">
</FrameLayout>
but when I was debugging, 'gg' got the right height value, 'hh' got -1. I'm doing this because I want to set the layout's height. How can I get the right value of LayoutParams?
–
–
You already did, onGlobalLayout is called when the view finishes laying out, that's why getHeight return non-zero pixel in height. If it's not drawn yet, getHeight will return 0
How can I get the right value of LayoutParams?
Nothing is wrong here, it's a right value. You get -1 from LayoutParams.height because it's MATCH_PARENT placeholder value, just like WRAP_CONTENT = -2. Android read this layout params value, then calculate the real size in pixel, which will be the value you get when calling getHeight.
I'm doing this because I want to set the layout's height
Just set the height value to the LayoutParams: layout.getLayoutParams().height = 100
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.