I need to get the size of the layout which height set as WRAP_CONTENT.
I tried to get it by calling
LinearLayout.getLayoutParams()
Which returns the height = -1 or -2 ( I know this is due to WRAP/MATCH Content ).
I've also tried
LinearLayout.getMeasuredHeight()
it returns 0.
How could I get the real size of the layout? Bellow is my sample code.
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
private void loadComponents() {
showMenuButton = findViewById(R.id.showMenuButton);
showMenuButton.setOnClickListener( v -> inflateMenu());
listNote = findViewById(R.id.listNote);
Point point = new Point();
getWindowManager().getDefaultDisplay().getRealSize(point);
LinearLayout thisLayout = findViewById(R.id.main_layout);
this.Y = thisLayout.getMeasuredHeight();
this.offsetY = point.y - Y;
}
Perhaps you could try this
DisplayMetrics displayMetrics = thisLayout.getResources().getDisplayMetrics();
int height = displayMetrics.heightPixels;
First of all notice that if your Linerlayout is not yet drawn both thisLayout.getHeight() and thisLayout.getWidth() will return 0.
So:
thisLayout.post(new Runnable(){
public void run(){
int height = thisLayout.getHeight();
int weight = thisLayout.getWidth();
}
});
You can use bellow code to get size of the layout whenever it changes.
// In you Activity / Fragment
private ViewTreeObserver.OnGlobalLayoutListener thisLayoutTreeObserver =
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// here you can get updated height of the View
thisLayout.getHeight();
}
};
@Override
public void onStart() {
super.onStart();
thisLayout.getViewTreeObserver()
.addOnGlobalLayoutListener(thisLayoutTreeObserver);
}
@Override
public void onStop() {
super.onStop();
thisLayout.getViewTreeObserver()
.removeOnGlobalLayoutListener(thisLayoutTreeObserver);
}
ViewTreeObserver
can be used to get notifications when global events, like layout, happen.
Here is an additional important consideration from the official documentation:
The returned ViewTreeObserver observer is not guaranteed to remain valid for the lifetime of this View. If the caller of this method keeps a long-lived reference to ViewTreeObserver, it should always check for the return value of
ViewTreeObserver.isAlive()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.