How to navigate from an activity to a fragment of another activity of a navigationBar?

0

Good morning

I have a problem in the navigation of my application in which I have a mainActivity (); where I have a series of fragments, now create a form activity in which for the moment I just need the one button to return me to a specific fragment of the activity that has the NavegationBar that contains the series of fragments.

This is the MainActivity with the navigationBar:

 public class MainActivity extends AppCompatActivity implements HomeFragment.OnFragmentInteractionListener,ProfileFragment.OnFragmentInteractionListener,TasksFragment.OnFragmentInteractionListener,GroupsFragment.OnFragmentInteractionListener {

    private BottomNavigationView bottomNavigationView;
    //private TextView titleView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.activity_main );


        // Forzar y cargar icono  en el action bar
        getSupportActionBar ().setDisplayShowHomeEnabled ( true );
        getSupportActionBar ().setIcon ( R.mipmap.ic_to_do_round );

        //inicializar con un fragmento
        HomeFragment homeFragment = new HomeFragment ();
        FragmentTransaction transaction = getSupportFragmentManager ().beginTransaction ();
        transaction.replace ( R.id.fragment_container,homeFragment);
        transaction.commit ();

        // manejo de bottomNavegationView
        bottomNavigationView = (BottomNavigationView) findViewById ( R.id.navigation );
        //titleView = (TextView) findViewById ( R.id.title_home );

        bottomNavigationView.setOnNavigationItemSelectedListener ( new BottomNavigationView.OnNavigationItemSelectedListener () {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                if (item.getItemId () == R.id.action_home) {
                    HomeFragment homeFragment = new HomeFragment ();
                    FragmentTransaction transaction = getSupportFragmentManager ().beginTransaction ();
                    transaction.replace ( R.id.fragment_container,homeFragment);
                    transaction.commit ();
                    //titleView.setText ( "Home" );
                } else if (item.getItemId () == R.id.action_profile) {
                    ProfileFragment profileFragment = new ProfileFragment ();
                    FragmentTransaction transaction = getSupportFragmentManager ().beginTransaction ();
                    transaction.replace ( R.id.fragment_container,profileFragment);
                    transaction.commit ();
                    //titleView.setText ( "Profile" );
                } else if (item.getItemId () == R.id.action_task) {
                    TasksFragment tasksFragment = new TasksFragment ();
                    FragmentTransaction transaction = getSupportFragmentManager ().beginTransaction ();
                    transaction.replace ( R.id.fragment_container,tasksFragment);
                    transaction.commit ();
                    //titleView.setText ( "Tasks" );
                } else if (item.getItemId () == R.id.action_group) {
                    GroupsFragment groupsFragment = new GroupsFragment ();
                    FragmentTransaction transaction = getSupportFragmentManager ().beginTransaction ();
                    transaction.replace ( R.id.fragment_container,groupsFragment);
                    transaction.commit ();
                    //titleView.setText ( "Groups" );
                }

                return true;

            }
        } );
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }
}

This is the fragment where you communicate to that activity by pressing a button:

    public class TasksFragment extends Fragment {

    ListView listTasks;
    ArrayList<TaskInformation> listaDeInformacionDeLasTareas;

    android.support.design.widget.FloatingActionButton floatingActionButton;

    private OnFragmentInteractionListener mListener;

    public TasksFragment() {
        // Required empty public constructor
    }


    // donde se pasan las variables de un fragmento a otro y donde se crean las partes logicas
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate ( savedInstanceState );
        if (getArguments () != null) {

        }
    }

    //donde se crean las partes visuales del fragmento
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

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

        //Floating button
        floatingActionButton = (FloatingActionButton) view.findViewById ( R.id.fab );
        floatingActionButton.setOnClickListener ( new View.OnClickListener () {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent (TasksFragment.this.getActivity (),TaskFormActivity.class);
                startActivity (intent);
            }
        } );

        //lista de tareas en el fragmento
        listTasks = (ListView) view.findViewById ( R.id.list_view_tasks );
        listaDeInformacionDeLasTareas = new ArrayList<TaskInformation> ();

        listaDeInformacionDeLasTareas.add ( new TaskInformation ( 1, "Realizar informe de reunion general", "00-00-0000", "Business" ) );

        AdapterTask adapterTask = new AdapterTask ( TasksFragment.this.getActivity (), listaDeInformacionDeLasTareas );
        listTasks.setAdapter ( adapterTask );

        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction ( uri );
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach ( context );
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException ( context.toString ()
                    + " must implement OnFragmentInteractionListener" );
        }
    }

    @Override
    public void onDetach() {
        super.onDetach ();
        mListener = null;
    }


    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

This is the activity where I am and I want to go to the TaskFragment fragment:

    public class TaskFormActivity extends AppCompatActivity {

    Button btnFormCreate;
    Button btnFormCancel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate ( savedInstanceState );
        supportRequestWindowFeature ( Window.FEATURE_NO_TITLE );
        setContentView ( R.layout.activity_task_form );

        btnFormCreate = (Button)findViewById ( R.id.btn_form_create );
        btnFormCancel = (Button)findViewById ( R.id.btn_form_cancel );

        btnFormCreate.setOnClickListener ( new View.OnClickListener () {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent (TaskFormActivity.this,MainActivity.class);
                startActivity (intent);
            }
        } );

        btnFormCancel.setOnClickListener ( new View.OnClickListener () {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent (TaskFormActivity.this,MainActivity.class);
                startActivity (intent);
            }
        } );


    }
}

Greetings

    
asked by Sergio Parada 22.03.2018 в 03:14
source

1 answer

0

We create an entire argument, which will be an application code static final int TASK_REQUEST = 1; in our MainActivity . Like this one could be created more for other actions.

In our Drawer in the item that we want to move to another activity, instead of using startActivity() we will use startActivityForResult() to wait for a result ..

int id = item.getItemId();
        if (id == R.id.nav_taskform) {
            // iniciar la actividad
            Intent intent = new Intent(MainActivity.this, TaskFormActivity.class);
            startActivityForResult(intent, TASK_REQUEST); // = 1
            // Cuando el usuario termina de utilizar la actividad subsiguiente
            // y vuelve, el sistema llama al método onActivityResult() de tu actividad.}

In the Form Activity we indicate the result at your convenience ..

        btnFormCreate.setOnClickListener ( new View.OnClickListener () {
            @Override
            public void onClick(View view) {
                Intent intent = getIntent();
                intent.putExtra("RESULTADO", 1);
                setResult(RESULT_OK, intent);
                finish();
            }
        } );

        btnFormCancel.setOnClickListener ( new View.OnClickListener () {
            @Override
            public void onClick(View view) {
                Intent intent = getIntent();
                intent.putExtra("RESULTADO", 0);
                setResult(RESULT_CANCELED);
                finish();
            }
        } );

Now we have to call the onActivityResult() method and depending on the result obtained, it will do one action or another, as we consider.

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Comprobamos si el resultado es cancelado
        if (resultCode == RESULT_CANCELED){
            Toast.makeText(this, "Resultado cancelado", Toast.LENGTH_LONG).show();
        } else {
            // En caso de ser OK
            //inicializar con un fragmento
            TasksFragment taskFragment = new TasksFragment();
            FragmentTransaction transaction = getSupportFragmentManager ().beginTransaction ();
            transaction.add( R.id.principal, taskFragment);
            transaction.commit ();
        }
    }

If we had more application codes, we would implement the onActivityResult in this other way ...

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == TASK_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            //inicializar con un fragmento
                TasksFragment taskFragment = new TasksFragment();
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction ();
                transaction.add( R.id.principal, taskFragment);
                transaction.commit ();
        } else {
          Toast.makeText(this, "Resultado cancelado", 
          Toast.LENGTH_LONG).show();
        }
    } else if (requestCode == OTRO_REQUEST) {
      //......implementa aquí tu código
      }
}

P.d. Although the question asked would have several possible answers.

    
answered by 22.03.2018 в 09:08