2014-04-04 33 views
0

我是新來Xamarin monoandroid,我在添加自定義視圖到我的佈局面臨的一個問題。我不知道我做錯了什麼。小幫助將是偉大的完整,這是我的自定義視圖類Xamarin的Android自定義視圖不加載

onDraw方法被調用,但我沒有得到輸出,沒有錯誤。

class PositionDrawer : View 
    { 
     private int count; 
     private int position; 
     private IPositionDrawer cinterface; 
     private Activity cactivity; 
     private int container; 
     private int p; 
     private ScoreFeed scoreFeed1; 
     private ScoreFeed scoreFeed2; 
     public PositionDrawer(Activity context, int count, int positionr, Activity cactivity) : 
      base (context) 
     { 
      //Initialize(); 
      this.cactivity = cactivity; 
      this.cinterface = cinterface; 
      this.count = count; 
      this.position = positionr; 
      //this.OnDraw(); 
      Initialize(); 
     } 

     private void Initialize() 
     { 
      //this.Invalidate(); 
      // this.SetMeasuredDimension(100, 100); 
      this.SetWillNotDraw(false); 
      Console.WriteLine(this.WillNotDraw()); 
     } 
     protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) 
     { 
      base.OnMeasure(widthMeasureSpec, heightMeasureSpec); 
     } 
     public void SetDrawer(int count, int positionr, Activity cactivity) 

     { 

      this.cactivity = cactivity; 
      this.cinterface = cinterface; 
      this.count = count; 
      this.position = positionr; 

      //base(cactivity); 
     } 

     protected override void OnDraw(Canvas canvas) 
     { 
      base.OnDraw(canvas); 
      Paint blue = new Paint(); 
      blue.Color = Color.Red; 

      float screenwidth = cactivity.WindowManager.DefaultDisplay.Width; 
      canvas.DrawRect(screenwidth * position-1, 0, screenwidth * position, 20, blue); 
      Console.WriteLine("SW1:" + screenwidth + "pos1:" + position); 
      // LinearLayout can =cactivity.FindViewById<LinearLayout>(container); 
      //cinterface.getview(this); 
     } 

    } 

和我使用以下代碼以添加視圖佈局。

View pd = new PositionDrawer(this, 3, position, this); 
container = FindViewById<LinearLayout>(Resource.Id.position); 
container.RemoveAllViews(); 
container.AddView(pd); 

在此先感謝。

回答

1

您需要執行正確的ctors。

當你實現了View類,那麼你必須至少有以下簽名的構造函數:

public PositionDrawer(IntPtr javaReference, JniHandleOwnership transfer) 
    : base(javaReference, transfer) { } 

如果你是在一個AXML佈局使用View,你還需要一個具有以下簽名:

public PositionDrawer(Context context, IAttributeSet attrs, int defStyle) 
    : base(context, attrs, defStyle) 

否則當您創建代碼View S,你需要給他們一些LayoutParameters否則他們不知道自己的尺碼。

+1

我已添加簽名的ctor。但我不知道如何初始化這個類。一個例子會幫助完整。 – Muthu