Xamarin Adapter FindViewById returns null

时间:2018-12-27 12:56:54

标签: android-listview xamarin.android

Not sure what I'm doing wrong here but FindViewById always returns null for my custom row view:

public override View GetView(int position, View convertView, ViewGroup parent) {
    var view = convertView;
    var item = items[position];

    if(view == null)
        view = context.LayoutInflater.Inflate(Resource.Layout.listview_row, null);

    var nameTextView = view.FindViewById<TextView>(Resource.Id.nameTextView);
    var priceTextView = view.FindViewById<TextView>(Resource.Id.priceTextView);

    nameTextView.Text = item.Name;
    priceTextView.Text = (item.Price ?? 0M).ToString("#.00");

    return view;
}

This is the view code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView id="@+id/nameTextView"
        android:layout_height="wrap_content"
        android:layout_width="0dp"
        android:layout_weight="0.8"
        android:layout_margin="5dp" />

    <TextView id="@+id/priceTextView"
        android:layout_height="wrap_content"
        android:layout_width="0dp"
        android:layout_weight="0.2"
        android:layout_margin="5dp" />
</LinearLayout>

The view inflates correctly but for some reason both TextViews are always null after the call to FindViewById.

I have tried cleaning and rebuilding the project but that did not work. Not sure why this is not working.

Thank you for any pointers.

1 个答案:

答案 0 :(得分:1)

您提供的ID用错误的方式,因此没有在资源设计器中注册

尝试一下:

 android:id="@+id/nameTextView"
 android:id="@+id/priceTextView"