我有一個帶有activity_main.xml佈局的MainActivity。我有一個自定義的ListView,這使得自己的佈局每個ListView項:嘗試訪問ListView佈局按鈕時出現NullPointerException
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: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
所以我怎麼設置OnClickListener這個ImageButton的?
SE在getView方法中使用onclicklistner –