nicolas asinovich
nicolas asinovich

Reputation: 3511

how to pass Bitmap from Fragment to Activity?

strong textApp have a fragment that contains image and i want to pass the image to activity use Bitmap when i click to set this image as wallpaper.

From Fragment :

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_view_pager, null);
        ImageView resultView = (ImageView) view.findViewById(R.id.result_image);

        resultView.setDrawingCacheEnabled(true);
        bitmap = resultView.getDrawingCache();

        resultView.setImageResource(pageNumber);
        return view;
    }

To Activity, when i click to set:

        case R.id.setForce:

                new TaskSetWallpaper(PreviewActivity.this).execute(bitmap);

                break;

Upvotes: 0

Views: 1034

Answers (1)

Lahiru Chandima
Lahiru Chandima

Reputation: 24068

You can create an interface in your fragment, which the parent activity of the fragment is expected to implement. Then, you can cast the activity to the interface in onAttach() of the fragment and call methods in the interface to notify events or pass data to parent activity.

Fragment:

public class MyFragment extends Fragment {
    private EventListener eventListener;

    public interface EventListener() {
        void onSetImage(Bitmap bitmap);
    }

    @Override
    public void onAttach(Activity a) {
        super.onAttach(a);
        if (a instanceof EventListener) {
            eventListener = (EventListener) a;
        } else {
            throw new UnsupportedOperationException("Parent activity should implement MyFragment.EventListener");
        }
    }
}

Parent activity:

public class ParentActivity extends AppCompatActivity implements MyFragment.EventListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //---------
        //---------
    }

    @Override
    void onSetImage(Bitmap bitmap){
        new TaskSetWallpaper(PreviewActivity.this).execute(bitmap);
    }
}

Upvotes: 2

Related Questions