我希望能够根据xml中定义的布局实例化一个新的自定义LinearLayout类。 无论我做什么,在运行时,LinearLayout 和我所有的 TextViews 都会抛出一个空引用异常。
transferListRow.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 Try 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 Try 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"));
1)因为您正在扩展 LinearLayout,所以在 XML 中查找的布局不需要具有 LinearLayout 包装器。而是只使用<merge> ... </merge>
.
2)在你的构造函数中,你必须调用inflator.Inflate(Resource.Layout.transferListRow, this);
。请注意此参数。这会将 XML 中定义的所有元素膨胀到 LinearLayout 中作为子元素。
3)当充气完成时,框架将在onFinishInflate()
中通知您,并且可以在findViewById()
中找到视图。因此,在onFinishInflate()
中,您可以将 TextView 分配给成员变量。
就是这样:)