一对夫妇首创这里定制的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>
谢谢提前。