Android layout 从子类TextView创建自定义Android UI元素时避免NullReferenceException
这里有几个第一——第一个Android应用程序,第一次使用MonoDroid(我对C#NET有很多经验) 在我的用户界面中,我想在TextView周围画一个边框,并在SO()上找到了一篇文章,建议对TextView进行子类化。我还发现了另一篇文章(),其中包含一些关于使用XML声明自定义Android UI元素的附加信息。(注意:示例文章中的所有代码都是用Java编写的,必须翻译成C#/MonoDroid环境。) 在emulator中运行代码时,我得到一个System.NullReferenceException:Object reference未设置为对象的实例 这是我的开箱即用活动1代码和子类TextView的代码Android layout 从子类TextView创建自定义Android UI元素时避免NullReferenceException,android-layout,textview,xamarin.android,Android Layout,Textview,Xamarin.android,这里有几个第一——第一个Android应用程序,第一次使用MonoDroid(我对C#NET有很多经验) 在我的用户界面中,我想在TextView周围画一个边框,并在SO()上找到了一篇文章,建议对TextView进行子类化。我还发现了另一篇文章(),其中包含一些关于使用XML声明自定义Android UI元素的附加信息。(注意:示例文章中的所有代码都是用Java编写的,必须翻译成C#/MonoDroid环境。) 在emulator中运行代码时,我得到一个System.NullReference
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):
提前感谢。Mono for Android在生成供Android使用的Java和布局XML文件时,会将名称空间名称小写 因此(如中所述),您需要使用
mbta.BorderedTextView
,而不是mbta.BorderedTextView
Mono for Android文档讨论了这个场景
<?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>