启动BottomSheetFragment获得结果

时间:2019-05-28 11:27:42

标签: java android android-fragments android-dialogfragment bottom-sheet

我想从BottomSheetFragment获得结果。我尝试通过

内部的getActivity().setResult(Activity.RESULT_OK, null);来完成此操作
    @Override
public void onDismiss(DialogInterface dialog) {
    getActivity().setResult(Activity.RESULT_OK, null);
    super.onDismiss(dialog);
}

但未调用活动的方法onActivityResult。我在做什么错了?

    @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Toast.makeText(this, requestCode, Toast.LENGTH_SHORT).show();
    super.onActivityResult(requestCode, resultCode, data);
}

对话框启动方法

BottomSheetDialogFragment bottomSheetFragment = new BottomSheetDialogFragment();
            Bundle bundle = new Bundle();
            bottomSheetFragment.setArguments(bundle);
            bottomSheetFragment.show(getSupportFragmentManager(), bottomSheetFragment.getTag());

2 个答案:

答案 0 :(得分:0)

onActivityResult()用于从另一个活动获取结果。

有关此内容的更多信息:https://developer.android.com/training/basics/intents/result

如果要将某些数据从Fragment发送到Activity,可以通过定义接口来实现,也可以通过将Activity强制转换为特定Activity来在Activity中调用方法。

class MainActivity extends AppCompatActivity {

 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
  YourBottomSheetDialogFragment bottomSheetFragment = new YourBottomSheetDialogFragment();
  Bundle bundle = new Bundle();
  bottomSheetFragment.setArguments(bundle);
  bottomSheetFragment.show(getSupportFragmentManager(), bottomSheetFragment.getTag());
 }

 public void setResultFromFragment(String data) {
  ...
 }
}

/**
* Calling Activity's method from Fragment
*/
class YourBottomSheetDialogFragment extends BottomSheetDialogFragment {

 @Override
 public void onCreate(@Nullable Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  ((MainActivity) getActivity()).setResultFromFragment("");
 }
}

答案 1 :(得分:0)

我决定按照 DEVV911

给我的建议实施接口
interface OnFinishedListener {

        void onFinished(ArrayList<TestCard> acceptList, ArrayList<TestCard> rejectList);

        void onFailure(Throwable t);
    }

将其添加到对话框的构造方法中

private TestActivityContract.OnFinishedListener onFinishedListener;

BottomSheetFragment(TestActivityContract.OnFinishedListener onFinishedListener) {
    this.onFinishedListener = onFinishedListener;
}

并在onDismiss中调用onFinished方法

    @Override
public void onDismiss(DialogInterface dialog) {
    super.onDismiss(dialog);
    onFinishedListener.onFinished(acceptList, rejectList);
}