Height and width of root element in Xamarin.Android

I am trying to get screen capture on the Xamarin.Android platform.

 public static Android.Content.Context Context { get; private set; } public override View OnCreateView(View parent, string name, Context context, IAttributeSet attrs) { MainActivity.Context = context; return base.OnCreateView(parent, name, context, attrs); } 

I am trying to figure out why the following rootView.Width and Height all time return 0.

 var rootView = ((Activity)MainActivity.Context).Window.DecorView.RootView; Console.WriteLine ("{0}x{1}", rootView.Width,rootView.Height); 

My ultimate goal is to capture a screenshot as an image and create a pdf.

+1
android xamarin
source share
2 answers

I do not know Xamarin, however, it seems to be similar to native Android for this solution.

When onCreateView () is called, views have not yet been measured. To get the dimensions of the view, you must attach a specific listener: onLayoutChangeListener .

Here is an example of native Android code:

 rootView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { int width = right - left; int height = bottom - top; v.removeOnLayoutChangeListener(this); // Remove the listener } }); 

You can find here a listener to be used for Xamarin

Hope this helps! :)

+1
source share

In onCreateView, the width and height of objects are not yet defined. They are identified at a later stage in the life cycle of an activity.

For this you need to use treeviewobserver.

Example with your rootview:

 rootView.ViewTreeObserver.GlobalLayout += (object sender, EventArgs e) => { Console.WriteLine ("{0}x{1}", rootView.Width,rootView.Height); }; 

In this method, the width and height will be known.

In addition, you want to take a snapshot of your root view, the best way to do this is to use this method, this will automatically output the raster image of the view to the variable b.

 rootView.DrawingCacheEnabled = true; Bitmap b = rootView.GetDrawingCache(true); 

Hope this helps you!

+1
source share

All Articles