How to pass data between fragments

后端 未结 13 2777
醉话见心
醉话见心 2020-11-22 07:03

Im trying to pass data between two fragmens in my program. Its just a simple string that is stored in the List. The List is made public in fragments A, and when the user cli

13条回答
  •  长情又很酷
    2020-11-22 07:30

    Fragment class A

    public class CountryListFragment extends ListFragment{
    
        /** List of countries to be displayed in the ListFragment */
    
        ListFragmentItemClickListener ifaceItemClickListener;   
    
        /** An interface for defining the callback method */
        public interface ListFragmentItemClickListener {
        /** This method will be invoked when an item in the ListFragment is clicked */
        void onListFragmentItemClick(int position);
    }   
    
    /** A callback function, executed when this fragment is attached to an activity */  
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    
        try{
            /** This statement ensures that the hosting activity implements ListFragmentItemClickListener */
            ifaceItemClickListener = (ListFragmentItemClickListener) activity;          
        }catch(Exception e){
            Toast.makeText(activity.getBaseContext(), "Exception",Toast.LENGTH_SHORT).show();
        }
    }
    

    Fragment Class B

    public class CountryDetailsFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
        /** Inflating the layout country_details_fragment_layout to the view object v */
        View v = inflater.inflate(R.layout.country_details_fragment_layout, null);
    
        /** Getting the textview object of the layout to set the details */ 
        TextView tv = (TextView) v.findViewById(R.id.country_details);      
    
        /** Getting the bundle object passed from MainActivity ( in Landscape   mode )  or from 
         *  CountryDetailsActivity ( in Portrait Mode )  
         * */
        Bundle b = getArguments();
    
        /** Getting the clicked item's position and setting corresponding  details in the textview of the detailed fragment */
        tv.setText("Details of " + Country.name[b.getInt("position")]);     
    
        return v;
        }
    
    }
    

    Main Activity class for passing data between fragments

    public class MainActivity extends Activity implements ListFragmentItemClickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    
    /** This method will be executed when the user clicks on an item in the listview */
    @Override
    public void onListFragmentItemClick(int position) {
    
        /** Getting the orientation ( Landscape or Portrait ) of the screen */
        int orientation = getResources().getConfiguration().orientation;
    
    
        /** Landscape Mode */
        if(orientation == Configuration.ORIENTATION_LANDSCAPE ){
            /** Getting the fragment manager for fragment related operations */
            FragmentManager fragmentManager = getFragmentManager();
    
            /** Getting the fragmenttransaction object, which can be used to add, remove or replace a fragment */
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    
            /** Getting the existing detailed fragment object, if it already exists. 
             *  The fragment object is retrieved by its tag name  *
             */
    Fragment prevFrag = fragmentManager.findFragmentByTag("in.wptrafficanalyzer.country.details");
    
            /** Remove the existing detailed fragment object if it exists */
            if(prevFrag!=null)
        fragmentTransaction.remove(prevFrag);           
    
            /** Instantiating the fragment CountryDetailsFragment */
      CountryDetailsFragment fragment = new CountryDetailsFragment();
    
            /** Creating a bundle object to pass the data(the clicked item's   position) from the activity to the fragment */ 
            Bundle b = new Bundle();
    
            /** Setting the data to the bundle object */
            b.putInt("position", position);
    
            /** Setting the bundle object to the fragment */
            fragment.setArguments(b);           
    
            /** Adding the fragment to the fragment transaction */
            fragmentTransaction.add(R.id.detail_fragment_container,   fragment,"in.wptrafficanalyzer.country.details");
    
            /** Adding this transaction to backstack */
            fragmentTransaction.addToBackStack(null);
    
            /** Making this transaction in effect */
            fragmentTransaction.commit();
    
        }else{          /** Portrait Mode or Square mode */
            /** Creating an intent object to start the CountryDetailsActivity */
            Intent intent = new Intent("in.wptrafficanalyzer.CountryDetailsActivity");
    
            /** Setting data ( the clicked item's position ) to this intent */
            intent.putExtra("position", position);
    
            /** Starting the activity by passing the implicit intent */
            startActivity(intent);          
          }
        }
     }
    

    Detailde acitivity class

    public class CountryDetailsActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        /** Setting the layout for this activity */
        setContentView(R.layout.country_details_activity_layout);
    
        /** Getting the fragment manager for fragment related operations */
        FragmentManager fragmentManager = getFragmentManager();
    
        /** Getting the fragmenttransaction object, which can be used to add, remove or replace a fragment */
        FragmentTransaction fragmentTransacton = fragmentManager.beginTransaction();
    
        /** Instantiating the fragment CountryDetailsFragment */
        CountryDetailsFragment detailsFragment = new CountryDetailsFragment();
    
        /** Creating a bundle object to pass the data(the clicked item's position) from the activity to the fragment */
        Bundle b = new Bundle();
    
        /** Setting the data to the bundle object from the Intent*/
        b.putInt("position", getIntent().getIntExtra("position", 0));
    
        /** Setting the bundle object to the fragment */
        detailsFragment.setArguments(b);
    
        /** Adding the fragment to the fragment transaction */
        fragmentTransacton.add(R.id.country_details_fragment_container, detailsFragment);       
    
        /** Making this transaction in effect */
        fragmentTransacton.commit();
    
        }
    }
    

    Array Of Contries

    public class Country {
    
    /** Array of countries used to display in CountryListFragment */
    static String name[] = new String[] {
            "India",
            "Pakistan",
            "Sri Lanka",
            "China",
            "Bangladesh",
            "Nepal",
            "Afghanistan",
            "North Korea",
            "South Korea",
            "Japan",
            "Bhutan"
    };
    }
    

    For More Details visit this link [http://wptrafficanalyzer.in/blog/itemclick-handler-for-listfragment-in-android/]. There are full example ..

提交回复
热议问题