Android with the intention to open a fragment from activity

I am implementing an application that has a gridview of images in one action and one fragment for each image that contains the image in full screen. When I click on any of the images in the grid, it should open the corresponding fragment. However, we cannot use the intention to do this. here is my code

public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { // TODO Auto-generated method stub if(position==0) { Intent i=new Intent(Gallery.this,ImageFrag1.class); startActivity(i); } 

and the fragment

 import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ImageFrag1 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.imagefrag1, container, false); } } 

This snippet is associated with the activity of ImagesSwipe. SO how do I achieve the transition between the grid element and its corresponding fragment. Thanks

+6
source share
2 answers

You do not need one fragment for one image. Just reuse one snippet with ImageView in its layout for each image.

Fragments are not called like "Actions through Intent." They can exist only as part of the Activity, for what they are intended. Think of them as a reusable user interface for activities. To add a fragment to an action, you must use the FragmentManager and FragmentTransaction , which provide all interactions with the fragments.

  FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(YourFragment.newInstance(), null); ft.commit(); 

Check out this guide from Google Docs for some basic things about GridView. In addition, you should read about Fragments . And here's a tutorial about your approach.

+5
source

You can check DialogFrament, here is an example .

Instead of using intentions, you use the FramentManager:

 if(position==0) { FragmentManager fm = getFragmentManager(); ImageFrag1 imageDialog = new ImageFrag1() ImageFrag1.show(fm, "image_title"); } 

And your dialog box becomes:

 import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ImageFrag1 extends DialogFragment { public ImageFrag1() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.dialog_fragment, container, false); } } 
+1
source

Source: https://habr.com/ru/post/949038/


All Articles