Lucho La Frazia
Lucho La Frazia

Reputation: 51

Pass information between two fragments

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;



public class ImagenesAlumnoActivity extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_imagenes_alumno);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);


    }



    public int getScreenWidth() {

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width=dm.widthPixels;

        return width;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_imagenes_alumno, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.ajustes:
                Intent ajuste = new Intent(ImagenesAlumnoActivity.this, AjusteActivity.class);
                Bundle b = getIntent().getExtras();
                String id = b.getString("id");
                ajuste.putExtra("id",id);
                startActivity(ajuste);
                return true;
            case R.id.modo_alumno:
                Intent intent = new Intent(ImagenesAlumnoActivity.this, ModoAlumnoActivity.class);
                Bundle b1 = getIntent().getExtras();
                String nombre = b1.getString("alumno");
                String id1 = b1.getString("id");
                intent.putExtra("alumno", nombre);
                intent.putExtra("id", id1);
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";
        private GridViewImageAdapter adapter1;
        public GridView gridView;
        private int anchoColumna;
        private List<Imagen> imagenes = new ArrayList<Imagen>();
        MediaPlayer player;


        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }




        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_imagenes_edicion, container, false);
            ArrayList<Imagen> imagenesParaMostrar = new ArrayList<Imagen>();

            gridView = (GridView) rootView.findViewById(R.id.grid_view);
            double mult = 0.8;
            inicializarGrilla(Constantes.CANTIDAD_COLUMNAS, Constantes.PADDING_GRILLA, gridView, mult);
            int position = this.getArguments().getInt(ARG_SECTION_NUMBER);
            imagenesParaMostrar.clear();
            for (Imagen imagen : Datos.imagenes){
                if ((imagen.getCategoria()) == position ) {
                    imagenesParaMostrar.add(imagen);
                }
            }
            adapter1 = new GridViewImageAdapter(this.getActivity(),imagenesParaMostrar,anchoColumna);
            gridView.setAdapter(adapter1);
            return rootView;
        }

        private void inicializarGrilla(int cantidadColumnas, int paddingGrilla, GridView gv, double mult) {
            anchoColumna = (int) (((this.getScreenWidth()* mult) - ((cantidadColumnas + 1) * paddingGrilla)) /cantidadColumnas);
            gv.setNumColumns(cantidadColumnas);
            gv.setColumnWidth(anchoColumna);
            gv.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
            gv.setPadding(paddingGrilla, paddingGrilla, paddingGrilla, paddingGrilla);
            gv.setHorizontalSpacing(paddingGrilla);
            gv.setVerticalSpacing(paddingGrilla);
            gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                    Imagen imagen = (Imagen) gridView.getAdapter().getItem(position);
                    player = MediaPlayer.create(getActivity(), imagen.getSonido());
                    player.start();
                }
            });


        }

        public int getScreenWidth() {

            DisplayMetrics displaymetrics = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
            int height = displaymetrics.heightPixels;
            int width = displaymetrics.widthPixels;
            return width;
        }

    }


    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        Bundle b = getIntent().getExtras();

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position);
        }

        @Override
        public int getCount() {
            // Show 4 total pages.
            return 5;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "PISTA";
                case 1:
                    return "ESTABLO";
                case 2:
                    return "EMOCIONES";
                case 3:
                    return "NECESIDADES";
                case 4:
                    return b.getString("alumno");
            }
            return null;
        }
    }

    public void loadBitmap(int resId, ImageView imageView) {
        BitmapWorkerTask task = new BitmapWorkerTask(imageView, getResources());
        task.execute(resId);
    }


}

I have diferents fragments with diferents images inside. I want to click one image and send it to another fragment. I saw a lot of solutions, using the Otto library would be easy. But in this case I use SectionsPagerAdapter that extends from FragmentPagerAdapter and I can't understand how to do it. Please help! Thanks

Upvotes: 0

Views: 77

Answers (2)

karimkhan
karimkhan

Reputation: 329

you can use a static class this. first(in fragment 1 ) pass value to fields of this class and in second fragment you can use it.

Upvotes: 0

jbr000
jbr000

Reputation: 441

I would recommend creating an Interface that calls back from your first Fragment to the parent Activity and passes the data you want to forward to the second Fragment. Then within the callback on the parent Activity, find your second Fragment by its tag and call a public method within the second Fragment that updates its UI with the forwarded data.

See the docs for explanation of how to do this:

http://developer.android.com/training/basics/fragments/communicating.html

Upvotes: 1

Related Questions