Parametric passage from one fragment to another

Asked

Viewed 512 times

1

I don’t know how to work with two fragments, I looked for some things here but I didn’t know how to look right.

Of Activity for another I use the Bundle and it works, but I don’t know how to use it with Fragment.

I’m working with Navigator Drawer that use fragments. one of the fragments I have a Listview and in this Listview I need to call another fragment with Listview as well.

Ex. first Fragment/Listview (Years) - 2016 - 2015 - 2014 - ....

Follow the code I’m using on the first fragment.

lv_Anos.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // pegas os valores do Text no linha //
        TextView txAno = (TextView) view.findViewById(R.id.tx_Ano);
        // chamar outro fragment e passar paramentro para ele //
        // Variável ->> Param_Ano  


     }
});

The Second Fragment/Listview - Editions

I need to receive the selected Year to generate the Json of the second fragment.

Variable Param_ano

new JSONTask().execute("http://www...../edicaoporano.php?Ano=" + Param_Ano);

1 answer

3


You should use Bundle as well, see an example:

To send to another Fragment

Seu_Fragment fragment = new Seu_Fragment(); 
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
bundle.putString("ano", Param_Ano); 
fragment.setArguments(bundle);
fragmentTransaction.replace(viewID, fragment);
fragmentTransaction.commit();

And to receive in the other Fragment

Bundle mBundle = new Bundle();
if(mBundle != null){
   mBundle = getArguments();
   String ano = mBundle.getString("ano"); 
} 

Now in the second Fragment, you have the String year populated with the value that came from the first Fragment

  • Thank you, Leonardo, it worked perfectly. But I ended up having another problem now, when entering the second Fragment does not have the back button for the first Fragment. Would you know how to do that? Thanks for the help.

  • You can go back through the physical button of the device, or you want to put a button?

  • Could be anyone, could be the physique of the device even if it’s easier.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.