how to go from a Fragment to an Actvity

1

What I'm trying to do is that by clicking on an item of the ListView that is in a fragment it will take me to Activity .

       @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        listaconimagenes adapter;

        frutas = getResources().getStringArray(R.array.arraycincofrutas);
        lista = (ListView) getActivity().findViewById(R.id.lista_frutas);
        adapter = new listaconimagenes(getActivity(), frutas, imagenes);
        lista.setAdapter(adapter);

        lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        Intent intent = new Intent(R.id.main_content, Main3Activity.class);
                        break;
                }
            }
        });

    }
}
    
asked by Sergio 13.06.2017 в 05:55
source

2 answers

4

What you are doing is wrong:

  Intent intent = new Intent(R.id.main_content, Main3Activity.class);

you need as the first parameter for the intent, the context , and as a second parameter the Activity you want to start.

In the case of a Fragment , you can get the context of the Activity by getActivity() . To start the Activity you must use the startActivity () :

  Intent intent = new Intent(getActivity(), Main3Activity.class);
  startActivity(intent);

Review the documentation .

This would be your code, which starts a new Activity by clicking on the first element of ListView (first element is position 0):

 lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position){
                case 0:
                   Intent intent = new Intent(getActivity(), Main3Activity.class);
                   startActivity(intent);
                    break;
            }
        }
    });
    
answered by 13.06.2017 / 16:40
source
3

You're doing very well, you just need to start the activity after the intent.

startActivity(intent);
    
answered by 13.06.2017 в 08:30