Android UINavigationController-like feature

后端 未结 4 979
梦如初夏
梦如初夏 2021-02-02 09:42

On the iPhone I use a Navigation Controller to push and pop Views from. Very handy.

Is there an equivalent in Android?

4条回答
  •  不知归路
    2021-02-02 10:31

    I made a Framework (github) to provide a hierarchical navigation pattern, with animations to provide sense of navigation, rather than launching new Activities every time.

    Android Basic Framework Image

    Here's how to use it:

    • Add the framework to your project as a Module
    • Add a new Java class in your project ("File - New - Java Class"). Note: If you are editing the Activity.java file that provides you the template, delete all its implementations and leave it empty.
    • Make it extend NavigationActivity
    • Implement all the NavigationActivity abstract methods

    (in Android Studio if you click Alt + insert and select implement - methods all the function definitions are automatically generated).

    public class NavigationTest extends NavigationActivity{
        @Override
        public Fragment firstFragment() {
            //return the first fragment that will be shown  
    
        }
    
        @Override
        public Boolean showBackButtonInFirstFragment() {
            //show back button already in the first Fragment
            //set to True if this activity is called by another Activity
            //the back button will then pop back to the previous Activity
    
        }
    
        @Override
        public Boolean showMasterDetailLayoutInTablets() {
            //set to false if you don't want a master-detail layout in tablets
    
        }
    }
    

    Presenting a new Fragment

    You can present a new fragment (with a nice animation) by calling the pushFragment method from NavigationActivity.

    public void pushFragment(Fragment newFragment, animationType animation, boolean showAsDetailFragmentIfPossible)
    

    newFragment (Fragment): New Fragment that will be presented

    animation (animationType): Animation type enum: RIGHT_TO_LEFT, BOTTOM_TO_TOP, FLIP

    showAsDetailFragmentIfPossible (boolean): If set as True, the user is in a Tablet, and you are using a master-detail layout, the Fragment will be shown in the detail Fragment (the panel in the right)!

    Since you can access the activity from any Fragment with the getActivity() method, you can show a new Fragment from the currently displaying Fragment. For example you can put this code within a button click listener:

    NextFragment f = new NextFragment();
    NavigationActivity nav =((NavigationActivity)getActivity());
    nav.pushFragment(f,NavigationActivity.animationType.RIGHT_TO_LEFT,false);
    

    You don't have to worry about implementing the back button behaviour. This is handled automatically by the NavigationActivity class.

提交回复
热议问题