Skip to content
This repository has been archived by the owner on May 1, 2024. It is now read-only.

Commit

Permalink
[Android] Always set a non-null Device.Info (#504)
Browse files Browse the repository at this point in the history
When we run under the context of layoutlib the `Context` object
that is created will not implement IDeviceInfoProvider. All this
means is that we will not get change notifications when the
orientation changes, but that's ok! This won't happen anyway.

If we instantiate the Device.Info object then everywhere else in
the code will be able to get access to the screen properties.

Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=44893
  • Loading branch information
alanmcgovern authored and StephaneDelcroix committed Nov 8, 2016
1 parent 84995a9 commit d43b8a2
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions Xamarin.Forms.Platform.Android/Forms.cs
Expand Up @@ -130,10 +130,7 @@ static void SetupInit(Context activity, Assembly resourceAssembly)
Device.info = null;
}

// probably could be done in a better way
var deviceInfoProvider = activity as IDeviceInfoProvider;
if (deviceInfoProvider != null)
Device.Info = new AndroidDeviceInfo(deviceInfoProvider);
Device.Info = new AndroidDeviceInfo(activity);

var ticker = Ticker.Default as AndroidTicker;
if (ticker != null)
Expand Down Expand Up @@ -190,17 +187,21 @@ static Color GetAccentColor()

class AndroidDeviceInfo : DeviceInfo
{
readonly IDeviceInfoProvider _formsActivity;
bool disposed;
readonly Context _formsActivity;
readonly Size _pixelScreenSize;
readonly double _scalingFactor;

Orientation _previousOrientation = Orientation.Undefined;

public AndroidDeviceInfo(IDeviceInfoProvider formsActivity)
public AndroidDeviceInfo(Context formsActivity)
{
_formsActivity = formsActivity;
CheckOrientationChanged(_formsActivity.Resources.Configuration.Orientation);
formsActivity.ConfigurationChanged += ConfigurationChanged;
// This will not be an implementation of IDeviceInfoProvider when running inside the context
// of layoutlib, which is what the Android Designer does.
if (_formsActivity is IDeviceInfoProvider)
((IDeviceInfoProvider) _formsActivity).ConfigurationChanged += ConfigurationChanged;

using (DisplayMetrics display = formsActivity.Resources.DisplayMetrics)
{
Expand All @@ -224,7 +225,11 @@ public override double ScalingFactor

protected override void Dispose(bool disposing)
{
_formsActivity.ConfigurationChanged -= ConfigurationChanged;
if (disposing && !disposed) {
disposed = true;
if (_formsActivity is IDeviceInfoProvider)
((IDeviceInfoProvider) _formsActivity).ConfigurationChanged -= ConfigurationChanged;
}
base.Dispose(disposing);
}

Expand Down

0 comments on commit d43b8a2

Please sign in to comment.