尝试访问ListView布局的Button时出现NullPointerException

时间:2017-05-27 01:59:32

标签: android android-layout listview

我有一个带有activity_main.xml布局的MainActivity。我有一个自定义ListView,它为每个ListView项呈现自己的布局:

ItemAdapter.java

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Loop loop = getItem(position);

    // Check if an existing view is being reused, otherwise inflate the view
    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
    }

在list_item.xml布局中,我有一个ImageButton:

<ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_more_vert_black_24dp"
        android:contentDescription="@string/descr_overflow_button"
        android:id="@+id/overflowMenu"
        android:layout_alignParentRight="true"/>

在MainActivity的onCreate中。我正在尝试将OnClickListener设置为该ImageButton:

    final ImageButton overflowMenu = (ImageButton) findViewById(R.id.overflowMenu);
    overflowMenu.setOnClickListener(new Button.OnClickListener(){

        @Override
        public void onClick(View arg0) {
            LayoutInflater layoutInflater
                    = (LayoutInflater)getBaseContext()
                    .getSystemService(LAYOUT_INFLATER_SERVICE);
            View popupView = layoutInflater.inflate(R.layout.item_popup, null);
            final PopupWindow popupWindow = new PopupWindow(
                    popupView,
                    Toolbar.LayoutParams.WRAP_CONTENT,
                    Toolbar.LayoutParams.WRAP_CONTENT);

            popupWindow.showAsDropDown(overflowMenu, 50, -30);

        }}
    );

然而,显然在MainActivity的onCreate上还没有生成ListView布局,因此无法找到ImageButton,我想?结果,我收到了这个错误:

  

java.lang.NullPointerException:尝试调用虚方法'void   android.widget.ImageButton.setOnClickListener(android.view.View $ OnClickListener)”   在空对象引用上

那么我应该如何在这个ImageButton上设置OnClickListener?

2 个答案:

答案 0 :(得分:0)

尝试将该ImageButton的OnClickListener放在Adapter的getView()方法中。

您可以使用查看充气程序来实现此目标

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    // INFLATE A VIEW
    View v=View.inflate(context,layout,null);
    // GET BUTTON HANDLER
    ImageButton overflowMenu = (ImageButton)v.findViewById(R.id.overflowMenu);
    // HANDLE CLICK EVENT
    overflowMenu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // DO YOUR WORK HERE
        }
    });
    // RETURN THAT VIEW
    return v;
}

希望它能解决

答案 1 :(得分:0)

替换此行

final ImageButton overflowMenu = (ImageButton) findViewById(R.id.overflowMenu);

使用此行

final ImageButton overflowMenu = (ImageButton) convertView.findViewById(R.id.overflowMenu);