27

I have an ImageView. I want to move from one fragment to another fragment on a click of an Imageview, the same way like we can move from one activity to another using

Intent i=new Intent(MainActivity.this,SecondActivity.class);
startActivity(i);

How can I do this? Can anyone explain to me step by step?

My codes are as follows:

mycontacts.class

public class mycontacts extends Fragment {
    public mycontacts() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        final View v = super.getView(position, convertView, parent);
        ImageView purple=(ImageView)v.findViewById(R.id.imageView1);
        purple.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
            // TODO Auto-generated method stub
            //how to go to tasks fragment from here???
            }
        });
        return view;

    } 
}

tasks.class

public class tasks extends Fragment {
    public tasks() { 
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

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

        return view;
    }
}
Abdul Mateen
  • 1,139
  • 1
  • 14
  • 21
anu_r
  • 1,602
  • 7
  • 30
  • 61

10 Answers10

73
purple.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Fragment fragment = new tasks();
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.content_frame, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
});

You write the above code...there we are replacing R.id.content_frame with our fragment.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
GvSharma
  • 2,632
  • 1
  • 24
  • 30
  • Fragment fragment=new tasks(); I am getting error `cannot convert fragments to task`. What to do? – anu_r Apr 22 '14 at 06:46
  • 2
    tasks extends fragment...so tasks is subclass of fragment only and make sure your import statements import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; if still errors then post your log messages – GvSharma Apr 22 '14 at 06:50
  • 1
    tasks fragment has the layout id `r.id.task`. and my current fragment has layout id `r.id.contact`. so what should i write inplace of `r.id.content_frame`? – anu_r Apr 22 '14 at 08:34
  • ok..you are now in MyContacts fragment na....how do you start that...?check that ..you might call to mycontacts fragment from somewhere by replacing a view....so here also you have to mention the same view .. hope this helps you. – GvSharma Apr 22 '14 at 08:58
  • Oh, how long I searched for the answer! Thank you! At first, though, the name of the variable tasks (?!) baffled. Then he casually remarked that he called his fragment tasks ! =) – gevaraweb Jan 27 '17 at 18:37
  • It works thanks, but how I can also change the selected item on the bar not only the view? – Aziz Nov 11 '20 at 07:02
  • I got it nvm: NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id./*id of nav bar*/); navigationView.setCheckedItem(R.id./*id of menu item to be highlighted*/); – Aziz Nov 11 '20 at 07:15
3

Add this code where you want to click and load Fragment.


Fragment fragment = new yourfragment();
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
Nimantha
  • 6,405
  • 6
  • 28
  • 69
3
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_profile, container, false);
    notification = (ImageView)v.findViewById(R.id.notification);

    notification.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FragmentTransaction fr = getFragmentManager().beginTransaction();
            fr.replace(R.id.container,new NotificationFragment());
            fr.commit();
        }
    });

    return v;
}
Akshay
  • 2,506
  • 4
  • 34
  • 55
sanju
  • 31
  • 1
2

When you are inside an activity and need to go to a fragment use below

getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();

But when you are inside a fragment and need to go to a fragment then just add a getActivity(). before, so it would become

getActivity().getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();

as simple as that.

The *TO_BE_REPLACED_LAYOUT_ID* can be the entire page of activity or a part of it, just make sure to put an id to the layout to be replaced. It is general practice to put the replaceable layout in a FrameLayout .

Shubham Rohila
  • 366
  • 2
  • 12
1

You can move to another fragment by using the FragmentManager transactions. Fragment can not be called like activities,. Fragments exists on the existence of activities.

You can call another fragment by writing the code below:

FragmentTransaction t = this.getFragmentManager().beginTransaction();
Fragment mFrag = new MyFragment();
t.replace(R.id.content_frame, mFrag);
t.commit();

here "R.id.content_frame" is the id of the layout on which you want to replace the fragment.

You can also add the other fragment incase of replace.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Ashok Singhal
  • 520
  • 1
  • 5
  • 10
  • Fragment fragment=new tasks(); I am getting error cannot convert fragments to task. What to do? – – anu_r Apr 22 '14 at 06:50
  • please check for the imports, Either use supportedFragment or Fragments – Ashok Singhal Apr 22 '14 at 06:52
  • 1
    asks fragment has the layout id r.id.task. and my current fragment has layout id r.id.contact. so what should i write inplace of r.id.content_frame? – anu_r Apr 22 '14 at 08:38
1

inside your onClickListener.onClick, put

getFragmentManager().beginTransaction().replace(R.id.container, new tasks()).commit();

In another word, in your mycontacts.class

public class mycontacts extends Fragment {

    public mycontacts() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View v = super.getView(position, convertView, parent);
        ImageView purple = (ImageView) v.findViewById(R.id.imageView1);
        purple.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                getFragmentManager()
                        .beginTransaction()
                        .replace(R.id.container, new tasks())
                        .commit();
            }
        });
        return view;

    }
}

now, remember R.id.container is the container (FrameLayout or other layouts) for the activity that calls the fragment

DragonFire
  • 3,722
  • 2
  • 38
  • 51
t_mo_t
  • 67
  • 8
0

If you're looking for the Kotlin version of the above code, you can do it in this way, and you call replaceFragment(RequiredFragment()) at onClickListener or wherever you want.

private fun replaceFragment(fragment: Fragment) {
val transaction = activity!!.supportFragmentManager.beginTransaction()
transaction.replace(R.id.frame, fragment)
transaction.commit()
}
Prateek
  • 502
  • 5
  • 16
0
private boolean loadFragment(Fragment fragment) {
        if (fragment != null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fl_fragment_container, fragment)
                    .commit();
            return true;
        }
        return false;
    }
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Kumar Santanu
  • 603
  • 1
  • 7
  • 14
0

in kotlin, put inside of your current running fragment button.setOnClickListener

    val bpfragment = TwoFragment()
    activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.fragment_container, bpfragment)?.commit()
Niaj Mahmud
  • 399
  • 3
  • 10
0
            val fragment = YourFragment3()
            val fm : FragmentManager= requireActivity().supportFragmentManager
            val ft: FragmentTransaction = fm.beginTransaction()
            ft.replace(R.id.container, fragment)
            ft.commit()
            (activity as MainActivity).binding.viewPager.setCurrentItem(2)
kamal
  • 1
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 23 '22 at 10:06