How to get callback from activity back to fragment using interface

南楼画角 提交于 2019-12-10 16:53:07

问题


I have a fragment, where I have a button to choose an image from a gallery. The gallery is open successfully, but when I choose the image, I do not get the result from activity. So I consider to use a callback (interface). However, I do know how.

Could you suggest me something please?

interface

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

in fragment click

@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);
        }
}

activity

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
}
  • here I would like to send result back to fragment using interface

回答1:


If you want to send data back to fragment class there can be a number of ways to do that:

First

  1. Create a public method in fragment class

  2. Call that method using the fragment object in activity class's onActivityResult()


Second

  1. Create an interface in activity and implement that interface in fragment. Then with the help of interface, send your data to fragment e.g.

Activity class

DataReceivedListener listener;

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

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

Fragment Class

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

    }

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

in Acitivity class

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


来源:https://stackoverflow.com/questions/40237415/how-to-get-callback-from-activity-back-to-fragment-using-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!