膨胀textview时出现空引用错误

我在Xamarin Android应用中将textview作为标题添加到listview.
按照ericosg对this SO question的回答中的说明,我将textview放在单独的axml文件中,然后尝试将其作为标头添加到我的列表视图中.

运行该应用程序会在活动试图使textview膨胀的行上收到以下错误:

[MonoDroid] UNHANDLED EXCEPTION:
[MonoDroid] Android.Content.Res.Resources+NotFoundException: Exception of type 'Android.Content.Res.Resources+NotFoundException' was thrown.
.
.
.
[MonoDroid]   --- End of managed exception stack trace ---
[MonoDroid] android.content.res.Resources$NotFoundException: Resource ID #0x7f050006 type #0x12 is not valid
[MonoDroid]     at android.content.res.Resources.loadXmlResourceParser(Resources.java:2250)  
etc.

这是我的代码:

在Activity .cs文件中:

myListView = FindViewById<ListView>(MyApp.Resource.Id.MyList);

        Android.Views.View myHeader = 
            this.LayoutInflater.Inflate(MyApp.Resource.Id.QuestionText, myListView);

        myListView.AddHeaderView(myHeader);

ListView定义:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ListView
        android:id="@+id/MyList"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
    </RelativeLayout>

标头定义:

<?xml version="1.0" encoding="utf-8"?>
        <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/QuestionText"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:drawableTop="@+id/MyImage" />

解决方法:

一些东西:

您正在尝试为ID资源而不是布局充气:

 Android.Views.View myHeader = this.LayoutInflater.Inflate(MyApp.Resource.Id.QuestionText, myListView);

LayoutInflater的Inflate调用仅接受Resource.Layout元素.更改为:

Android.Views.View myHeader = this.LayoutInflater.Inflate(Resource.Layout.Header, myListView);

其次,在您的Header.xml布局文件中,TextView android:drawableTop不接受ID引用,因此,当LayoutInflator尝试构建布局时,它将抛出InflateException.

From the docs

android:drawableTop

The drawable to be drawn above the text.

May be a reference to another resource, in the form “@[+][package:]type:name” or to a theme attribute in the form “?[package:][type:]name”.

May be a color value, in the form of “#rgb”, “#argb”, “#rrggbb”, or “#aarrggbb”.

将其更改为对有效颜色或可绘制对象(@ drawable / MyImage)的引用或内联颜色声明(#fff).

最后,如果不使用适配器,则无法将子视图或标题视图添加到ListView:

> https://*.com/a/7978427/1099111
> https://*.com/a/7978427/1099111

考虑重新阅读Xamarin docs for ListViews and Adapters以更好地理解该主题.

上一篇:C#-Android NfcV读取标签始终位于0x00之前


下一篇:c#-将Icon属性与Xamarin.Forms中的嵌入式图像一起使用