2011-12-13 108 views
1

一對夫婦首創這裏定製的Android UI元素時避免一個NullReferenceException - 使用MonoDroid的第一款Android應用程序,並第一時間(我有很多與C#.net經驗)。創建從子類的TextView

在我的用戶界面我想提請圍繞一個TextView邊框,發現一個帖子上SO(2026873)所推薦的子類的TextView。我還發現了另一篇文章(2695646),其中提供了一些關於使用XML聲明自定義Android UI元素的額外信息。 (注意:示例文章中的所有代碼均爲Java,必須轉換爲C#/ MonoDroid環境。)

當我在模擬器中運行代碼時,我得到一個System.NullReferenceException:對象引用未設置爲實例的一個對象。

這是我出的現成活動1代碼和子類的TextView的代碼。

namespace MBTA 
{ 
    [Activity(Label = "MBTA", MainLauncher = true, Icon = "@drawable/icon")] 
    public class Activity1 : Activity 
    { 
     protected override void OnCreate(Bundle bundle) 
     { 
      base.OnCreate(bundle); 
      SetContentView(Resource.Layout.Main); 
     } 
    } 

    public class BorderedTextView : TextView 
    { 
     public BorderedTextView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { } 
     public BorderedTextView(Context context, IAttributeSet attrs) : base(context, attrs) { } 
     public BorderedTextview(Context context) : base(context) { } 

     protected override void OnDraw (Android.Graphics.Canvas canvas) 
     { 
      base.OnDraw (canvas); 

      Rect rect = new Rect(); 
      Paint paint = new Paint(); 

      paint.SetStyle(Android.Graphics.Paint.Style.Stoke); 
      paint.Color = Android.Graphics.Color.White; 
      paint.StrokeWidth = 3; 

      GetLocalVisibleRect(rect); 
      canvas.DrawRect(rect, paint); 
     } 
    } 
} 

我Main.axml佈局如下:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res/MBTA"  
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <LinearLayout 
     android:orientation="horizontal" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:layout_weight="1"> 
     <MBTA.BorderedTextView 
      android:text="DATE" 
      android:textSize="15pt" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:gravity="center_horizontal|center_vertical" 
      android:layout_weight="1"/> 
    </LinearLayout> 
</LinearLayout> 

而且我attrs.xml文件如下(其BuildAction的設置爲AndroidResource):

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="BorderedTextView"> 
     <attr name="android:text"/> 
    <attr name="android:textSize"/> 
    <attr name="android:layout_width"/> 
    <attr name="android:layout_height"/> 
    <attr name="android:gravity"/> 
    <attr name="android:layout_weight"/> 
    </declare-styleable> 
</resources> 

謝謝提前。

回答