Skip to content

Instantly share code, notes, and snippets.

@paul-kiar
Created November 8, 2018 20:25
Show Gist options
  • Save paul-kiar/4fd33366dfaf39be771ffa13cfc23955 to your computer and use it in GitHub Desktop.
Save paul-kiar/4fd33366dfaf39be771ffa13cfc23955 to your computer and use it in GitHub Desktop.
CarouselViewRenderer Position Fix for Android
using Android.Support.V7.Widget;
using System;
using System.Reflection;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(CarouselView), typeof(Apm.Mobile.Common.Droid.Renderers.CarouselViewRendererFix))]
namespace Apm.Mobile.Common.Droid.Renderers
{
// this is an implementation of this pull request: https://github.com/xamarin/Xamarin.Forms.CarouselView/pull/13/files
public class CarouselViewRendererFix : Xamarin.Forms.Platform.CarouselViewRenderer
{
private Type _layoutManagerType;
private MethodInfo _layoutManagerResetMethod;
private FieldInfo _layoutManagerPositionOriginField;
protected RecyclerView.LayoutManager LayoutManager => Control?.GetLayoutManager();
protected Type LayoutManagerType
{
get
{
if ( _layoutManagerType == null )
{
_layoutManagerType = LayoutManager?.GetType();
}
return _layoutManagerType;
}
}
protected MethodInfo LayoutManagerResetMethod
{
get
{
if (_layoutManagerResetMethod == null)
{
_layoutManagerResetMethod = LayoutManagerType?.GetMethod("Reset", BindingFlags.NonPublic | BindingFlags.Instance);
}
return _layoutManagerResetMethod;
}
}
protected FieldInfo LayoutManagerPositionOriginField
{
get
{
if (_layoutManagerPositionOriginField == null)
{
_layoutManagerPositionOriginField = LayoutManagerType?.GetField("_positionOrigin", BindingFlags.NonPublic | BindingFlags.Instance);
}
return _layoutManagerPositionOriginField;
}
}
public int CurrentLayoutManagerPosition => (int?)LayoutManagerPositionOriginField?.GetValue(LayoutManager) ?? 0;
protected void ResetLayoutManager(int position)
{
if (CurrentLayoutManagerPosition != position)
{
var parameters = new object[1];
parameters[0] = position;
LayoutManagerResetMethod?.Invoke(LayoutManager, parameters);
}
}
protected override void OnLayout(bool changed, int left, int top, int right, int bottom)
{
base.OnLayout(changed, left, top, right, bottom);
ResetLayoutManager(Element.Position);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment