【问题标题】:Use interface in bottom sheet在底部工作表中使用界面
【发布时间】:2017-12-13 12:08:51
【问题描述】:

我想在我的片段和底部工作表中添加一个界面,当底部工作表完成一个动作(比如选择一个按钮)时,它会在我的背景片段中调用,但是当我调用界面时它返回 null 并且在我的动作完成后从不调用!

这是我填充界面的代码,但从未调用过条件:

if(responseListener != null){
  responseListener.onData( 200,message);
}

我的代码:

public class FilterBottomSheet extends BottomSheetDialogFragment implements View.OnClickListener {

    private BottomSheetBehavior.BottomSheetCallback mBottomSheetBehaviorCallback = new BottomSheetBehavior.BottomSheetCallback() {

        @Override public void onStateChanged(@NonNull View bottomSheet,int newState){
            if(newState==BottomSheetBehavior.STATE_HIDDEN) {
                dismiss();
            }
        }
    }

    @Override public void onSlide(@NonNull View bottomSheet,float slideOffset){}};

    @SuppressLint("RestrictedApi")
    @Override
    public void setupDialog(Dialog dialog, int style) {
        super.setupDialog(dialog, style);
        View contentView = View.inflate(getContext(), R.layout.bottom_sheet_filter, null);
        dialog.setContentView(contentView);

        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) ((View) contentView.getParent())
                .getLayoutParams();
        CoordinatorLayout.Behavior behavior = params.getBehavior();

        if (behavior != null && behavior instanceof BottomSheetBehavior) {
            ((BottomSheetBehavior) behavior).setBottomSheetCallback(mBottomSheetBehaviorCallback);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.btnDoAction:
            fillActionInterface("TEST");
            dismiss();
            break;
        }
    }

    public OnResponseListener responseListener;

    private void fillActionInterface(String message) {

        if (responseListener != null) {
            responseListener.onData(200, message);
        }
    }
}

所以我不能在我的另一个片段中调用接口。 (因为它从不调用)

【问题讨论】:

  • 可以指定错误日志吗?
  • @Benjithbinja 我没有出错,我的问题是接口没有调用另一个片段。

标签: java android interface fragment bottom-sheet


【解决方案1】:

您应该在 BottomSheet 的 onAttach 方法中初始化您的接口实例:

@Override 
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        responseListener = (ResponseListener) getParentFragment();
    } catch(Exception e) {
       //handle exception
    }
}

请注意,如果您想从片段显示 BottomSheet 对话框并在片段中获取回调,您需要使用 getChildFragmentManager() 而不是 getFragmentManager() 调用。

如果您使用 getFragmentManager() 显示它,您将在 onAttach 方法中获得强制转换异常。

查看this 链接,了解 ChildFragmentManager 和 FragmentManager 之间的区别。

【讨论】:

  • 我添加了一个答案,我不知道在哪里使用 getChildFragmentManager(),请回答:)
  • 在显示底部工作表对话框的地方调用它:bottomSheet.show(getChildFragmentManager(), "TAG");
  • 非常感谢,现在另一个问题是我如何将数据从我的片段发送到底部工作表片段?
  • Hello Put getChildFragmentManager() 在 OnAttch 中仍然出现崩溃
猜你喜欢
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 2020-10-06
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多