bottomSheetDialog.getDelegate().getFragment() 报错
时间: 2024-03-02 07:54:35 浏览: 26
如果在调用 `bottomSheetDialog.getDelegate().getFragment()` 方法时出现了报错,可能是因为 BottomSheetDialog 的内部实现发生了改变,导致该方法无法使用。这时,你可以尝试使用以下替代方法:
1. 在 BottomSheetDialogFragment 中定义一个公共方法,用于获取该 Fragment 实例。例如:
```java
public class MyBottomSheetDialogFragment extends BottomSheetDialogFragment {
// 公共方法,用于获取 Fragment 实例
public static MyBottomSheetDialogFragment newInstance() {
return new MyBottomSheetDialogFragment();
}
// ...
}
```
2. 在 Activity 中,先创建 BottomSheetDialogFragment 实例,然后通过 `getDialog()` 方法获取 BottomSheetDialog 实例,最后调用该 Dialog 的 show() 方法显示弹窗。例如:
```java
MyBottomSheetDialogFragment fragment = MyBottomSheetDialogFragment.newInstance();
fragment.show(getSupportFragmentManager(), "dialog");
BottomSheetDialog dialog = (BottomSheetDialog) fragment.getDialog();
```
3. 在 Activity 中,通过 Dialog 的 findViewById() 方法来获取弹窗中的 View,然后再通过 View 的 getTag() 方法来获取该 View 对应的 Fragment 实例。例如:
```java
BottomSheetDialog dialog = new BottomSheetDialog(this);
View view = LayoutInflater.from(this).inflate(R.layout.my_bottom_sheet_layout, null);
dialog.setContentView(view);
dialog.show();
MyBottomSheetDialogFragment fragment = (MyBottomSheetDialogFragment) getSupportFragmentManager().findFragmentByTag(view.getTag().toString());
```
注意:在第二种方法中,需要在 BottomSheetDialogFragment 的 onCreateView() 方法中设置弹窗的 View,并给该 View 设置一个 tag,用于在后续的操作中获取该 View 对应的 Fragment 实例。例如:
```java
public class MyBottomSheetDialogFragment extends BottomSheetDialogFragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_bottom_sheet_layout, container, false);
view.setTag(this); // 给 View 设置一个 tag,用于后续获取该 Fragment 实例
// ...
return view;
}
// ...
}
```