【问题标题】:ViewStub Null exception inflateViewStub Null 异常膨胀
【发布时间】:2014-07-04 00:00:32
【问题描述】:

我得到一个错误

07-04 01:49:56.325: E/AndroidRuntime(9693): java.lang.NullPointerException

在事务完成后尝试在 Fragment 中膨胀 ViewStub

sendMessageView = ((ViewStub) rootView
            .findViewById(R.id.send_message_viewstub)).inflate();

这里是 XML

<ViewStub
        android:id="@+id/send_message_viewstub"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:inflatedId="@+id/panel_import"
        android:layout="@layout/fragment_send_message" />

【问题讨论】:

  • 请显示您的所有代码;整个 logcat 和您的所有源代码。

标签: android viewstub


【解决方案1】:

同意 Shawnic,您向我们展示的错误行并不能说明太多。我可以告诉你,使用片段比活动要复杂一些。

但是话虽如此,我认为您不能使用片段作为包含的布局? 在您的问题的上下文中,片段到底是什么或在哪里?

片段有自己的类文件,负责扩充布局以用作片段。

我也很关心你发布的这部分:

sendMessageView = ((ViewStub) rootView
        .findViewById(R.id.send_message_viewstub)).inflate();

现在我有这方面的经验,但已经有一段时间了,我不确定你的这部分代码是否正确?

Android 推荐你这样写:

 ViewStub stub = (ViewStub) findViewById(R.id.stub);
 View inflated = stub.inflate();

在你的代码中,什么样的对象是

sendMessageView 

您可能希望首先将您的代码更改为此,以确保我们不知道 Android 为何建议我们这样做,但我们可能应该这样做。

【讨论】:

    【解决方案2】:

    如果您总是要在此 ViewStub 中填充相同的布局,则最好使用 include 标记。

    <include layout="@layout/fragment_send_message />
    

    include 在运行时将自己替换为指定的布局,并允许您的布局既模块化又可读。

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多