Get click id on the previous Fragment listview

Asked

Viewed 565 times

0

I have a Fragment that loads a listview. This listview is populated with a hashmap getting the values from the bd. When I click on item 1,2,3... of the list, it opens a Fragmentb(details). How do I get the item id clicked on fragment with data populated in fragmentB? I want when you click Step 1, open the details of the _id 1 item in the database in Fragmentb.

Follow the codes of the two Fragments below:

    public class FragmentEtapasCaminhoFr extends Fragment {

private ListView lv;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_etapascaminho1, container, false);

    BD bd = new BD(getActivity());
    List<Etapas> buscarEtapas = bd.buscarListaEtapas();
    ArrayList<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();                

    for (int i = 0; i < buscarEtapas.size(); i++) { 
    HashMap<String, String> listEtapa = new HashMap<String, String>();

    listEtapa.put("nomeEtapas", String.valueOf(buscarEtapas.get(i).getId())+" - "+ buscarEtapas.get(i).getNomeEtapas());
    listEtapa.put("km", String.valueOf( buscarEtapas.get(i).getDistancia())+" Km");
    listEtapa.put("albergues", String.valueOf(buscarEtapas.get(i).getNumeroAlbergues())+" Albergues");
    aList.add(listEtapa);

    }

    String[] fromFr = new String []{"nomeEtapas", "km", "albergues"};
    int layoutNativo = R.layout.fragment_etapascaminho;
    int[] toFr = new int[]{R.id.txtNomeEtapa, R.id.txtEtapaDistancia, R.id.txtEtapaAlbergues};

    lv = (ListView) view.findViewById(R.id.listViewEtapas);                                      //os componentes que estão dentro do """layoutNativo""" 
    lv.setAdapter(new SimpleAdapter(getActivity(), aList, layoutNativo, fromFr, toFr));    //será inflado, q nesse caso é o "fragment_caminhos"
    lv.setOnItemClickListener(new ListView.OnItemClickListener(){

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                switch (position) {
                case 0:
                Fragment fragment1 = new FragmentCaminhosDetalhes();
                FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.replace(R.id.content_frame, fragment1,"content_frame");
                ft.addToBackStack("stak");
                ft.commit();
                break;

                case 1:
                    Fragment fragment2 = new FragmentCaminhosDetalhes();
                    FragmentTransaction ft2 = getActivity().getSupportFragmentManager().beginTransaction();
                    ft2.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    ft2.replace(R.id.content_frame, fragment2,"content_frame");
                    ft2.addToBackStack("stak");
                    ft2.commit();
                    break;
            }


            //Toast.makeText(getActivity(), "O item "+(position + 1)+" \""+aList.get(position)+"\" foi clicado", Toast.LENGTH_SHORT).show();

        }

    });

    return(view);

}

}

Below is the Fragmentb Code(details)

    public class FragmentCaminhosDetalhes extends Fragment {

private TextView txt;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_detalhescaminho, container, false);


    BD bd = new BD(getActivity());
    Caminhos buscar = bd.buscarCaminho();


    txt = (TextView) view.findViewById(R.id.textView3);
    TextView txt1 = (TextView) view.findViewById(R.id.textView2);
    txt.setText("Conteúdo do menu "+buscar.getId());
    txt1.setText("Nome: "+buscar.getNomeCaminhos());       //  PRECISO OBTER NOS TXT OS DADOS DOS 
                                                           //   ITENS 1,2,3 do FRAGMENT ANTERIOR


    return(view);
}

}

1 answer

1

How you’re instilling the Fragment just before adding it in the layout, you can pass the position by Argument, and it becomes available in any part of the next Fragment. I left commented the changes I made in your code.

public class FragmentEtapasCaminhoFr extends Fragment {
    private ListView lv;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_etapascaminho1, container, false);

        // Codigo e mais codigo...

        for (int i = 0; i < buscarEtapas.size(); i++) { 
            HashMap<String, String> listEtapa = new HashMap<String, String>();

            listEtapa.put("nomeEtapas", String.valueOf(buscarEtapas.get(i).getId())+" - "+ buscarEtapas.get(i).getNomeEtapas());
            listEtapa.put("km", String.valueOf( buscarEtapas.get(i).getDistancia())+" Km");
            listEtapa.put("albergues", String.valueOf(buscarEtapas.get(i).getNumeroAlbergues())+" Albergues");

            // Guardar o id, assim quando o item for clicado é possivel recuperá-lo
            listaEtapa.put("id", buscarEtapas.get(i).getId());

            aList.add(listEtapa);
        }

        lv.setOnItemClickListener(new ListView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        Fragment fragment1 = new FragmentCaminhosDetalhes();

                        Bundle args = new Bundle();

                        HashMap<String, String> item = (HashMap<String, String>) parent.getItemAtPosition(position); // Recupero o item clicado
                        args.set("ID", item.get("id")); // Recupero o id do item clicado e passo como Arguments para o novo Fragment

                        fragment1.setArguments(args);

                        FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                        ft.replace(R.id.content_frame, fragment1,"content_frame");
                        ft.addToBackStack("stak");
                        ft.commit();
                    break;

                    case 1:
                        Fragment fragment2 = new FragmentCaminhosDetalhes();

                        Bundle args = new Bundle();

                        HashMap<String, String> item = (HashMap<String, String>) parent.getItemAtPosition(position); // Recupero o item clicado
                        args.set("ID", item.get("id")); // Recupero o id do item clicado e passo como Arguments para o novo Fragment

                        fragment2.setArguments(args);

                        FragmentTransaction ft2 = getActivity().getSupportFragmentManager().beginTransaction();
                        ft2.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                        ft2.replace(R.id.content_frame, fragment2,"content_frame");
                        ft2.addToBackStack("stak");
                        ft2.commit();
                    break;
                }
            }
        });

        return(view);
    }
}

Already in the Fragment that will be added, just recover the arguments and recover the id of the item that will be detailed.

public class FragmentCaminhosDetalhes extends Fragment {
    private TextView txt;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_detalhescaminho, container, false);

        // Recupero o ID passado como argumento do Fragment anterior
        Integer id = getArguments().getInt("id");

        BD bd = new BD(getActivity());
        Caminhos buscar = bd.buscarCaminho(id);

        // Popular os dados do caminho no layout deste fragment

        txt = (TextView) view.findViewById(R.id.textView3);

        TextView txt1 = (TextView) view.findViewById(R.id.textView2);
        txt.setText("Conteúdo do menu "+buscar.getId());
        txt1.setText("Nome: "+buscar.getNomeCaminhos());

        return(view);
    }
}
  • friend, thank you so much for your help. But I’m running into a problem. how do I use this line listEtapa.put("id", searchEtapas.get(i).getId()); if the hashmap only accepts <String,String>? You would have to create a new Hashmap String,Object? and funny what else: args.set("ID", item.get("id")); eclipse does not accept "set".

  • You can use the toString class Integer and then make a parseInt, or else do what you said: use as Object and leave the Adapter use the toString in Strings

Browser other questions tagged

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