Reputation: 910
Afternoon SO.
I am sure the answer to this question is out there - but I have no ****ing clue where, so let me begin;
I have developed previously for the Android platform and the Windows platform, but I am stumped as to how I can reference an Android Layout/Activity from XAML using Xamarin.Forms . I have found examples using native controls and sub-classed controls but I cannot seem to marry the different concepts up to have XAML reference an entire View!?
Any help would be appreciated...
using Android.Content;
using Android.Runtime;
using Android.Util;
using Android.Views;
namespace PlatformControls.Droid
{
[Register("xxxxControl")]
public class xxxxControl : View
{
Context mContext;
#region Private Members
#endregion
#region Constructors
public xxxxControl(Context context)
: base(context)
{
init(context);
LayoutInflater mInflator = LayoutInflater.From(context);
View layout = mInflator.Inflate(Resource.Layout.GanttCellControlLayout, null, false);
// cannot addView() !?
// dont know what to do - other than attempt to drown myself in the toilet sink
}
public xxxxControl(Context context, IAttributeSet attrs)
: base(context, attrs)
{
init(context);
}
public xxxxControl(Context context, IAttributeSet attrs, int d)
: base(context)
{
init(context);
}
#endregion
#region Public Properties
#endregion
#region Methods
#endregion
private void init(Context context)
{
mContext = context;
}
}
}
Upvotes: 0
Views: 1110
Reputation: 21
Maybe you used to need a custom renderer but that does not seem to be the case anymore now that Native Embedding is available. A solution like this is possible
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:androidLocal="clr-namespace:NativeControls.Droid;assembly=NativeControls.Droid;targetPlatform=Android"
xmlns:formsAndroid="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.Platform.Android;targetPlatform=Android"
x:Class="Wrappers.CP.CustomControlWrapper">
<ContentView.Content>
<androidLocal:MyView x:Arguments="{x:Static formsAndroid:Forms.Context}"
Text ="I am rendered by an Android custom control"/>
</ContentView.Content>
</ContentView>
Speaking as a relative newcomer to this what does not seem to be very obvious is exactly what type of object MyView in the code above is. An answer that seems to work is that it should be inherited from LinearLayout. Then code something like this
// Get the UI controls from the loaded layout:
Inflate(Context, Resource.Layout.MyView, this);
this.myText = FindViewById<TextView>(Resource.Id.SomeContent);
// Add controls to the layout here if needed
var layout = FindViewById<LinearLayout>(Resource.Id.MyView_outerlayout);
Can be added to the init function in the example above, to obtain references to the controls in the layout or to get the layout so that additional controls can be added.
Upvotes: 1