How to navigate in fragments?

后端 未结 1 1652
北恋
北恋 2020-12-28 22:20

So I am using Tabs and seeking for this kind of navigation:

tab1 -- > inside 1 -- > inside2

tab2 -- > inside 3 -- > inside 4

tab3 -- > inside 5

相关标签:
1条回答
  • 2020-12-28 22:54

    I like to let my host Activity handle all transitions, so what I do in my fragments is create an interface to handle navigation. For example, you could add this interface to your Tab1Fragment:

    public interface Callback {
        public void onButtonBClicked();
    }
    

    Then in your TabsFragmentActivity, implement Tab1Fragment.Callback, which will require you to implement onButtonBClicked(). Here's an example of how you could implement this method:

    @Override
    public void onButtonBClicked() {
    
        Fragment anotherFragment = Fragment.instantiate(this, AnotherFragment.class.getName());
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(R.id.realtabcontent, anotherFragment);
        ft.addToBackStack(null);
        ft.commit();
    }
    

    Almost done. Next, you need to do is get a reference to this callback in your fragment. This is typically achieved in the onAttached() method. For example:

    @Override
    public void onAttach(Activity activity) {
    
        super.onAttach(activity);
        try {
            mCallback = (Callback) activity;
        }
        catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement " + Callback.class.getName());
        }
    }
    

    And, finally, in your OnClickListener, call mCallback.onButtonBClicked().

    0 讨论(0)
提交回复
热议问题