我有一个片段布局是抽屉,看起来像这样的时候:的NullPointerException设置的ListView适配器(DrawerLayout)
fragment_overview.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffe887" />
<!-- The navigation drawer -->
<ListView android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="multipleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
而该片断的Java类:
OverviewFragment.java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_overview, container, false);
mlistOptions = getResources().getStringArray(R.array.list_options);
mDrawerLayout = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
mDrawerList = (ListView) getActivity().findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(getActivity(),
R.layout.simple_list_item_1, mlistOptions));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
return root;
}
有了这个代码在资源文件夹中:
<string-array name="list_options">
<item>Ship</item>
<item>Map</item>
<item>Mail</item>
<item>Settings</item>
<item>Logout</item>
</string-array>
并将此作为一个列表项:
simple_list_item_1.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp"
android:textColor="@android:color/black"
android:textStyle="italic">
然而,当setAdapter方法运行在java类中它会产生这个错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
在该方法调用中实际上可能发生了什么错误?它是一个片段,所以我们需要getActivity作为第一个参数,布局文件只是对简单文件的引用,而optionslist只是资源文件夹中的数组列表。什么可以为null?
在此先感谢!
更换,如果''left_drawer的ListView里面''fragment_overview布局,然后使用'root',而不是'getActivity()'访问它 –
谢谢这工作! – boking