2017-06-21 17 views
0

下午。在XAML中創建和使用Android視圖

我相信這個問題的答案在那裏 - 但我沒有****線索在哪裏,所以讓我開始吧;

我以前爲Android平臺和Windows平臺開發過,但我很難理解如何使用Xamarin.Forms從XAML引用Android佈局/活動。 我已經找到了使用原生控件和子類控件的例子,但是我似乎無法將不同的概念結合起來讓XAML引用整個視圖!?

任何幫助,將不勝感激......

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; 
     } 
    } 
} 

回答

1

也許你習慣需要一個定製的渲染,但似乎並沒有這樣的情況了,現在原生嵌入功能可用。 像這樣的解決方案是可行

<?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> 

談到作爲一個相對較新的這似乎什麼並不很明顯的恰恰是在代碼什麼類型的對象MyView的的上面。 似乎有效的答案是它應該從LinearLayout繼承。 然後代碼是這樣的

// 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); 

可以添加到初始化函數在上面的例子中,獲得在佈局中的控件引用或獲得的佈局,使額外的控制可以加入。