ViewStub NullPointerException

时间:2011-10-11 18:14:05

标签: android nullpointerexception viewstub

我的视图存根有问题。

这是我的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>

我在视图存根中膨胀的布局文件如下:

     <?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来填充它。 任何想法导致这个问题以及如何解决。

非常感谢

Log cat中的错误: enter image description here

2 个答案:

答案 0 :(得分:3)

它没有工作的原因: 根据文件: http://developer.android.com/reference/android/view/ViewStub.html#inflate()

您正在“膨胀的布局资源”上执行findViewById,这是您正在寻找的列表视图。

答案 1 :(得分:1)

而不是使用

ListView people=(ListView)inflated.findViewById(R.id.friends);

我用过

ListView people=(ListView)stub.inflate();

它不知道为什么??但它确实:))

相关问题