ListPopupWindow getListView在创建后返回nullpointerexception

时间:2016-04-30 10:19:33

标签: java android

我正在使用ListPopupWindow

@NonNull
private ListPopupWindow createListPopupWindow() {
    ListPopupWindow listPopupWindow = new ListPopupWindow(mContext);
    listPopupWindow.setBackgroundDrawable(mContext.getDrawable(R.drawable.custom_dropdown));
    listPopupWindow.setDropDownGravity(Gravity.CENTER);
    listPopupWindow.setWidth(ListPopupWindow.WRAP_CONTENT);
    listPopupWindow.setHeight(ListPopupWindow.WRAP_CONTENT);
    listPopupWindow.setModal(true);
    return listPopupWindow;
}

当我试着打电话时:

listPopupWindow.setAdapter(new DropDownlistAdapter(mContext,
                armAwayItems));
View container = (View) listPopupWindow.getListView().getParent();

它始终返回NPE,但此方法已存在于ListPopupWindow

 Attempt to invoke virtual method 'android.view.ViewParent android.widget.ListView.getParent()' on a null object reference

当我试着打电话时

listPopupWindow.getListView().setDividerHeight(1);

listPopupWindow.getListView().setDivider(...);

所以listPopupWindow.getListView()总是返回NULL。

2 个答案:

答案 0 :(得分:0)

试试这个

if(listPopupWindow != null){
listPopupWindow.setAdapter(new DropDownlistAdapter(mContext,
            armAwayItems));
View container = (View) listPopupWindow.getListView().getParent();

What is a Null Pointer Exception, and how do I fix it?

答案 1 :(得分:0)

对于那些在答案部分寻找答案的人(不过M D的评论早得多):

getListView()将返回null,直到您调用listPopupWindow的show()方法