gpt4 book ai didi

c# - 膨胀 TextView 时出现空引用错误

转载 作者:太空宇宙 更新时间:2023-11-03 13:51:18 25 4
gpt4 key购买 nike

我在 Xamarin Android 应用程序中将 TextView 作为标题添加到 ListView 。按照 ericosg 对 this SO question 的回答中的说明进行操作,我将 textview 放在一个单独的 axml 文件中,然后尝试将它作为标题添加到我的 ListView 中。

运行该应用程序会在 Activity 尝试扩充 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);

LayoutInflaterInflate 调用只接受 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 添加 subview 或标题 View :

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

关于c# - 膨胀 TextView 时出现空引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34622418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com