我有一個活動,其中有很多片段。當在一個特定的片段上,我膨脹了一個菜單,當點擊膨脹的MenuItem時,我應該調用Fragment類的一個方法,它改變片段內的約束佈局的佈局參數。問題是我正在嘗試更改約束佈局上的NPE。setLayoutParams從活動片段內的佈局
這些都是我想調用的方法:
public void searcherOpen() {
searchLayout.setLayoutParams(new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT));
searchText.setFocusable(true);
}
public void searcherClose() {
searchLayout.setLayoutParams(new ConstraintLayout.LayoutParams(0, 0));
searchText.setFocusable(false);
}
這些是調用方法的菜單項:
getMenuInflater().inflate(R.menu.patient_fragment_menu, menu);
final MenuItem search = menu.findItem(R.id.menu_search);
final MenuItem close_search = menu.findItem(R.id.menu_search_close);
search.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
patientFragment.searcherOpen();
search.setVisible(false);
close_search.setVisible(true);
return true;
}
});
close_search.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
patientFragment.searcherClose();
search.setVisible(true);
close_search.setVisible(false);
return true;
}
});
這是我如何定義在活動中的片段的onCreate:
patientFragment = (PatientFragment)getFragmentManager().findFragmentByTag("patientFragment");
這是錯誤:
當你想調用searcherOpen()
的堆棧跟蹤
06-06 14:52:23.314 3682-3682/com.medishare.zeeromed E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.medishare.zeeromed, PID: 3682
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.medishare.zeeromed.fragments.PatientFragment.searcherOpen()' on a null object reference
at com.medishare.zeeromed.DrawerActivity$3.onMenuItemClick(DrawerActivity.java:255)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:959)
at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:623)
at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:154)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22393)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:173)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:938)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)