java - 嵌套 findViewById

标签 java android android-layout android-xml findviewbyid

我在 LinearLayout 内的相对布局内访问 TextView 时遇到问题

假设我在文件 row.xml 中有这些 View

<LinearLayout>
    <TextView android:id="@+id/title" />
    <RelativeLayout android:id="@+id/a_parent">
        <TextView android:id="@+id/a">
    </RelativeLayout>
    <RelativeLayout android:id="@+id/b_parent">
        <TextView android:id="@+id/b">
    </RelativeLayout>
</LinearLayout>

现在我想更改 Activity 中 TextView 的值

LayoutInflater li=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout temp=(LinearLayout) li.inflate(R.layout.row, null);
((TextView)temp.findViewById(R.id.title)).setText("This is title");
RelativeLayout rl=(RelativeLayout)temp.findViewById(R.id.a_parent);
((TextView)rl.findViewById(R.id.a)).setText("an this is the content of a");

我可以成功设置 id 'title' 的 TextView,但是在接近最后一行时出现错误。它说错误是由 android.content.res.Resources$NotFoundException: String Resource ID #0x1 引起的

谁能告诉我出了什么问题,如何修复它,以及为什么代码不能按我的预期工作?

谢谢

最佳答案

您的异常是字符串的 ResourcesNotFoundException。您是否使用 getString 设置 TextView 的值?如果是这样,您确定该字符串存在于您的 strings.xml 文件中吗?如果没有,您是否可以使用 R.string.name 而不是 R.id.name 引用您的 View 之一?看来您修改了发布代码,如果您准确发布了原始代码中所做的操作以及完整的堆栈跟踪,可能会更容易提供帮助。

有时,资源会出现问题,因为 R 文件未包含最新代码。我还会尝试重建/清理您的项目,看看是否有帮助。

关于java - 嵌套 findViewById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12534815/

相关文章:

java - 组合语法可以工作,但是当词法分析器和解析器语法分离时会出现错误?

java - 如何将值从 MainActivity 传递到 ServiceConnection?

android-layout - R.JAVA 和资源找不到的问题

java - Mockito mockStatic 无法解析符号

java - 使用 LocalDate 存储日期

java - Thread.sleep导致android程序崩溃

android.widget.RelativeLayout$LayoutParams 无法转换为 android.widget.AbsListView$LayoutParams

android - android渐变中的角度属性

java - 找出给定 uid 所属的 LDAP 组

android - ICS 中的全屏覆盖