How do I open a new fragment from another fragment

2019-01-14 10:25发布

I tried making a navigation between fragments. I've got the NewFragment.java with the new fragment working. My problem is:

How do I make this onClickListener run NewFragment.java correctly?

button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {

        Intent i = new Intent(getActivity(), NewFragment.class);
        startActivity(i);

    }
});

FYI: This is from inside a fragment (I don't know if that matters).

6条回答
太酷不给撩
2楼-- · 2019-01-14 10:44

Use this,

AppCompatActivity activity = (AppCompatActivity) view.getContext();
Fragment myFragment = new MyFragment();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).addToBackStack(null).commit();
查看更多
▲ chillily
3楼-- · 2019-01-14 10:49

Add following code in your click listener function,

NextFragment nextFrag= new NextFragment();
getActivity().getSupportFragmentManager().beginTransaction()
             .replace(R.id.Layout_container, nextFrag, "findThisFragment")
             .addToBackStack(null)
             .commit();

The string "findThisFragment" can be used to find the fragment later, if you need.

查看更多
成全新的幸福
4楼-- · 2019-01-14 10:50
 Fragment fr = new Fragment_class();
             FragmentManager fm = getFragmentManager();
            FragmentTransaction fragmentTransaction = fm.beginTransaction();
            fragmentTransaction.add(R.id.viewpagerId, fr);
            fragmentTransaction.commit();

Just to be precise, R.id.viewpagerId is cretaed in your current class layout, upon calling, the new fragment automatically gets infiltrated.

查看更多
劫难
5楼-- · 2019-01-14 10:51

You should create a function inside activity to open new fragment and pass the activity reference to the fragment and on some event inside fragment call this function.

查看更多
贼婆χ
6楼-- · 2019-01-14 10:52

This is more described code of @Narendra's code,

First you need an instance of the 2nd fragment. Then you should have objects of FragmentManager and FragmentTransaction. The complete code is as below,

Fragment2 fragment2=new Fragment2();
FragmentManager fragmentManager=getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_main,fragment2,"tag");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

Hope this will work. Sometimes you may get getSupportFragmentManager() instead of getFragmentManager().

查看更多
别忘想泡老子
7楼-- · 2019-01-14 11:00
@Override
public void onListItemClick(ListView l, View v, int pos, long id) {
    super.onListItemClick(l, v, pos, id);
    UserResult nextFrag= new UserResult();
    this.getFragmentManager().beginTransaction()
    .replace(R.id.content_frame, nextFrag, null)
    .addToBackStack(null)
    .commit();  
}
查看更多
登录 后发表回答