0

I am working inside a Fragment that has a ListView. When the user clicks on a list row, I want to open another fragment that should show another ListView.

This is the method I have for now:

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String topic = String.valueOf(parent.getItemAtPosition(position));

        Log.d("Comunidad",topic);
        //PASA VALOR SELECCIONADO AL SIGUIENTE FRAGMENT
    }
});

What is the best way to open the new Fragment from inside this method?

Thank you.

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
user3713806
  • 27
  • 2
  • 6

4 Answers4

2

Add a FrameLayout to your preferred activity's layout to call FragmentA (the fragment to be opened onClick):

<FrameLayout
     android:layout_width="match_parent"
     android:id="@+id/outer_frame"
     android:layout_height="wrap_content">
</FrameLayout>

and then replace outer_frame (FrameLayout) with your FragmentA by doing this:

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String topic = String.valueOf(parent.getItemAtPosition(position));

          Log.d("Comunidad",topic);
          getSupportFragmentManager().beginTransaction()
              .replace(R.id.outer_frame, new FragmentA())
              .commit();

        }
    });
Nilesh Singh
  • 1,750
  • 1
  • 18
  • 30
1

inside onClick of listview

Fragment2 new_frag = new Fragment2();
return new_frag;
Gilbert Mendoza
  • 405
  • 1
  • 7
  • 16
1
       // Inside your onClick method
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container, new MyFragment());
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
Saurabh Padwekar
  • 3,888
  • 1
  • 31
  • 37
0

I might be wrong but i think what you want to do is not possible, because fragments are not intended to be open inside an already opened activity... What you could do is prepare the activity with the fragment and then change it's content when you want to... Might be wrong tho...

  • You can open differents fragments in one activity... You can add fragment by xml or inside a framelayout. Since you use a framelayout, you could replace or add another fragment in this same framelayout. – Blo Dec 27 '16 at 01:07