Press the button on a screen that is a fragment and go to another fragment. How to do?

1

I have a class of type Fragment and I would like that when the user clicks on the button it would go to another screen that is fragment .. how can I do this?

public class AlertaFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState) {

        View view =  inflater.inflate(R.layout.fragment_alerta, container, false);

        FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        return view;
    }
}

@EDIT

I put it like this: He makes the argument red ...

final FragmentTransaction ft = getFragmentManager().beginTransaction();
CadastroAlertaFragment cadastro = new CadastroAlertaFragment();
ft.replace(R.id.cadastro_frag, cadastro, cadastro.getTag());
ft.commit();

Error:

Error:(167, 48) error: incompatible types: CadastroAlertaFragment cannot be converted to Fragment
    
asked by anonymous 02.02.2017 / 14:17

2 answers

3

Within the onClick method of your button, you can do this using the replace() method of FragmentTransaction . See:

final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
ft.replace(R.id.details, new NewFragmentToReplace(), "NewFragmentTag"); 
ft.commit(); 

And if you want to go back to the previous fragment , see more details on the addToBackStack() .

    
02.02.2017 / 14:29
3

There is another way to do this. And maybe it's simpler than it sounds.

  

Fragment

View.OnClickListener onClickHandler = new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        FragmentActivity mainActivity = getActivity();

        if(mainActivity instanceof suaActivityPrincipal)
        ((suaActivityPrincipal) mainActivity).setCurrentItemPager(1); // 1 = ID do fragment
    }

};
  

Activity

public void setCurrentItemPager(int id){
    viewPager.setCurrentItem(id); // viewPager = substitua pelo seu viewPAger
}

It's a little simpler to do this. It makes a reference to Activity parent to be able to change the current fragment .

Change the line: setCurrentItemPager(1) to the ID of the fragment you want to show.

    
02.02.2017 / 16:47