我正在創建一個模態底部表,它將從用戶那里獲取過濾條件。我想將它與 Fragment (HomeFragment) 一起使用,并通過在我的 BottomSheetFragment 的介面中傳遞 onButtonClicked 方法內的字串值并在我的 HomeFragment 中獲取這些值來獲取從我的 HomeFragment 內的 BottomSheet 中選擇的按鈕。即使在 onAttach 中對其進行了初始化,當我在 Log.i 中顯示其狀態時,它仍顯示為 null。
這是我的模態底部表類:
public class StartupSearchBottomSheet extends BottomSheetDialogFragment {
private StartupSearchBottomSheetListener sbsListener;
Button show;
String checkedCatButton, checkedSortButton;
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.startupsearch_bottomsheet, container, false);
show = v.findViewById(R.id.show);
checkedCatButton = "Technology";
checkedSortButton = "companyName";
show.setOnClickListener(v -> {
Log.i(TAG, "432: " sbsListener); //shows me null here
sbsListener.onButtonClicked(checkedCatButton, checkedSortButton);
dismiss();
});
return v;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try{
Log.i(TAG, "431: onAttach invoked");
sbsListener = (StartupSearchBottomSheetListener) getParentFragment();//initialized my listener here
}catch(ClassCastException e){
throw new ClassCastException(context " must implement StartupSearchBottomSheetListener.");
}
}
}
這是我得到的錯誤:
2022-04-03 21:38:25.330 4465-4465/com.phtlearning.nivesh E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.phtlearning.nivesh, PID: 4465
java.lang.NullPointerException: Attempt to invoke interface method 'void com.phtlearning.nivesh.StartupSearchBottomSheet$StartupSearchBottomSheetListener.onButtonClicked(java.lang.String, java.lang.String)' on a null object reference
at com.phtlearning.nivesh.StartupSearchBottomSheet$1.onClick(StartupSearchBottomSheet.java:183)
at android.view.View.performClick(View.java:7575)
at android.view.View.performClickInternal(View.java:7548)
at android.view.View.access$3600(View.java:837)
at android.view.View$PerformClick.run(View.java:28933)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8057)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:620)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1011)
uj5u.com熱心網友回復:
聽起來您的片段沒有正確嵌套,因此它沒有父片段。添加時請務必使用getChildFragmentManager,而不是getSupportFragmentManager,否則getParentFragment()將回傳null。
添加這樣的空檢查也是一個好主意
sbsListener = (StartupSearchBottomSheetListener) getParentFragment();
if( sbsListener == null ) {
throw new RuntimeException("Could not get listener");
}
因此,如果您希望為非空的變數為空,您會立即知道。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/460282.html
標籤:爪哇 安卓 安卓片段 android-bottomsheet 对话框
上一篇:無法創建com.example.retrotest.ui.AlbumsViewModel類的實體
下一篇:為什么打開片段我需要雙擊選單項?
