我希望能够基于 xml 中定义的布局实例化一个新的自定义 LinearLayout 类。无论我做什么,在运行时,LinearLayout 和我所有的 TextViews 都会抛出一个空引用异常。
传输列表行.axml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:padding="5dp">
<TextView
android:id="@+id/transferSerial"
android:layout_width="0dp"
android:layout_weight=".30"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:padding="5dp"
android:gravity="center" />
<TextView
android:id="@+id/transferModel"
android:layout_width="0dp"
android:layout_weight=".30"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:padding="5dp"
android:gravity="center" />
<TextView
android:id="@+id/transferSite"
android:layout_width="0dp"
android:layout_weight=".30"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:padding="5dp"
android:gravity="center" />
<Button
android:id="@+id/transferDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:padding="5dp"
android:gravity="center"
android:src="@drawable/delete" />
TransferListRow.cs 尝试 1:
sealed class TransferListRow : LinearLayout
{
private readonly Context _context;
public TransferListRow(Context context, string serial, string model, string site)
:base(context)
{
_context = context;
LayoutInflator inflator = (LayoutInflator) _context.GetSystemService(Context.LayoutInflaterService);
inflator.Inflate(Resource.Layout.transferListRow, null);
TextView s = (TextView) FindViewById(Resource.Id.transferSerial);
s.Text = serial;
TextView m = (TextView) FindViewById(Resource.Id.transferModel);
m.Text = model;
TextView st = (TextView) FindViewById(Resource.Id.transferSite);
st.Text = site;
}
}
TransferListRow.cs 尝试 2:
sealed class TransferListRow : LinearLayout
{
private readonly Context _context;
public TransferListRow(Context context, string serial, string model, string site)
:base(context)
{
_context = context;
LinearLayout layout = (LinearLayout) FindViewById(Resource.Layout.transferListRow);
TextView s = (TextView) layout.FindViewById(Resource.Id.transferSerial);
s.Text = serial;
TextView m = (TextView) layout.FindViewById(Resource.Id.transferModel);
m.Text = model;
TextView st = (TextView) layout.FindViewById(Resource.Id.transferSite);
st.Text = site;
AddView(s);
AddView(m);
AddView(st);
}
}
最终目标是从我的主要活动中能够在按钮单击事件中执行以下操作:
mainLayout.AddView(new TransferListRow(this, "serial", "model", "site"));