android - ViewStub 空指针异常

标签 android nullpointerexception viewstub

我对 View stub 有疑问。

这是我java文件中的ViewStub

ViewStub stub = (ViewStub) findViewById(R.id.stub1);
ArrayAdapter<String> content=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,files);
View inflated=stub.inflate();
ListView people=(ListView)inflated.findViewById(R.id.friends);
people.setAdapter(content);

这是我初始化 Viewstub 的 xml

    <?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id = "@+id/linear_details" >
    <include layout="@layout/home_back_next_bar" />
    <ViewStub android:id="@+id/stub1" android:inflatedId="@+id/showlayout"
android:layout="@layout/layout1" android:layout_width="fill_parent"
android:layout_height="wrap_content"/>  

</LinearLayout>
</merge>

我在 View stub 中膨胀的布局文件如下:

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

此代码在创建 ListView 的实例以填充它时给我一个 NullPointerException。 任何想法是什么导致了这个问题以及如何解决。

提前致谢

日志猫中的错误: enter image description here

最佳答案

它不起作用的原因: 根据文档: http://developer.android.com/reference/android/view/ViewStub.html#inflate ()

您正在对“膨胀的布局资源”执行 findViewById,这正是您正在寻找的 ListView 。 .

关于android - ViewStub 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7730528/

相关文章:

java - Java 8 中的三元运算符,使用 Maven 进行编译

java - arrayList 字符串搜索 : NullPointerException

android - 单个 viewStub 中的多个布局

android - 有没有办法在 RecyclerView 中使用 ViewStub?

android - 后退按钮的确定/取消对话框

java - 什么是NullPointerException,我该如何解决?

java - android.widget.LinearLayout 无法转换为 android.widget.ImageView?

android - ViewStub 在有条件地扩充多个布局时引发错误

android - 在 Fragment 中,初始化 OpenCV4Android 的正确位置是什么?

使用 PagerAdapter 中的 getPageWidth 时,Android ViewPager 滚动问题只有一项