片段中的Nullpointer异常(初始化listview)

时间:2013-12-17 14:31:08

标签: java android listview android-fragments

以下是我尝试在Fragment中显示列表的代码,该代码在尝试初始化NullPointerException时始终报告ListView

public class PortfolioFragment extends ListFragment {

ListView l;
ArrayAdapter<String> adapter;
List<String> list;

public PortfolioFragment() {
    // Required empty public constructor
}

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);                

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    list = MainActivity.globalArrayTest;
    l = (ListView) getView().findViewById(android.R.id.list);
    adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
    l.setAdapter(adapter);

    return inflater.inflate(R.layout.fragment_portfolio, container, false);

}

我在这一行收到错误:

l = (ListView) getView().findViewById(android.R.id.list);

3 个答案:

答案 0 :(得分:4)

更改为

View v = inflater.inflate(R.layout.fragment_portfolio, container, false);
l = (ListView) v.findViewById(android.R.id.list);
return v; 

你应该在xml中有以下内容

<ListView android:id="@android:id/list"

或覆盖onActivityCreated并使用getListView()

另外你可以使用下面的黑带评论这比上面更好。

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
            l = getListView(); // since you extend ListFragment
}

答案 1 :(得分:3)

由于您要延长ListFragment,因此应使用getListView()代替findViewByIdsetListAdapter应在onCreateView之后调用(onActivityCreated内,例如)

答案 2 :(得分:0)

这是另一种解决方法,尽管我只扩展了Fragment

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
                                          Bundle SavedInstanceState) {

            View rootView = inflater.inflate(R.layout.fragment_item, container, false);


            ListView itemList = (ListView)rootView.findViewById(R.id.itemListView);


     String[] items = {"Alpha", "Orange", "Pineapple", "Venus", "Echo", "Pent", "Mouse", 
                      "Phoenix", "Dent", "Sloppy"};


         ArrayAdapter<String> adapter = new ArrayAdapter<String>(rootView.getContext(),
                      R.layout.text_row, items);

  itemList.setAdapter(new ArrayAdapter<>(rootView.getContext(), 
                             R.layout.fragment_item, items));

    itemList.setAdapter(adapter);


    return (rootView);
}