【问题标题】:How to get callback from activity back to fragment using interface如何使用接口将活动回调返回到片段
【发布时间】:2017-03-07 08:27:04
【问题描述】:

我有一个片段,其中有一个按钮可以从图库中选择图像。图库已成功打开,但是当我选择图像时,我没有从活动中获得结果。所以我考虑使用回调(接口)。不过,我知道怎么做。

你能给我一些建议吗?

界面

public interface CallbackListener {
    void onPhotoTake(String url);
}

在片段点击中

@OnClick(R.id.addPhoto) void photo() {
        if (isStoragePermissionGranted()) {
            Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            context.startActivityForResult(i, RESULT_LOAD_IMAGE);
        }
}

活动

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
}
  • 这里我想使用接口将结果返回到片段

【问题讨论】:

  • 您好,您能否发布一些代码以向我们提供有关它已实现的更多信息?
  • 我编辑了我的问题并添加了一些代码

标签: java android android-fragments interface onactivityresult


【解决方案1】:

如果您想将数据发送回片段类,可以有多种方法:

第一

  1. 在片段类中创建一个公共方法

  2. 使用活动类的onActivityResult()中的片段对象调用该方法@


第二

  1. 在活动中创建一个接口并在片段中实现该接口。然后在接口的帮助下,将您的数据发送到片段 例如

活动类

DataReceivedListener listener;

public void setDataReceivedListener(DataReceivedListener listener) {
    this.listener = listener;
}

public interface DataReceivedListener {
    void onReceived(int requestCode, int resultCode, Intent data)
}

片段类

class fragment extends Fragments implements yourActivityClassName.DataReceivedListener {
    @Override
    void onReceived(int requestCode, int resultCode, Intent data) {

    }

    onViewCreated(...) {
        ((yourActivityName) getActivity()).setDataReceivedListener(this);
    }
}

在活动课上

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (listener != null) {
        listener.onActivityResult(requestCode, resultCode, data);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    相关资源
    最近更新 更多