How to get width and height of view in onCreate method

You can get the width and height of the view through the view's getWidth() and getHeight().
However, what may disappoint you is that if you call these two functions directly inside the onCreate method, you will get 0.
why?
This is because, when onCreate is called, the content of the view is being filled by LayoutInflater to fill the xml layout.
This process populates the layout, but doesn't set the size of the view for now.
So when exactly does the view get its own size?
In fact, it is after Layout, and layout is after onCreate is called.
So, what should we do if we want to get the size of the view in the onCreate method?
In fact, there is still a solution, which is to use the post method of the view.
Without further ado, look at the code:
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate (savedInstanceState);
	setContentView(R.layout.main);
	View view = findViewById(R.id.main_my_view);
	view.post(new Runnable() {	
		// Get size of view after layout
		@Override
		public void run() {
			Log.d(TAG, "view has width: "+view.getWidth() + " and height: "+view.getHeight());
		}
	});
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326904946&siteId=291194637