使用Android中的工具栏实现正确的后退导航和主页按钮处理

时间:2016-04-12 07:43:14

标签: android android-fragments navigation-drawer android-navigationview

我在同一个活动中使用单个活动和多个片段(附加截图)来提供无缝导航。但在实现最新的工具栏和导航视图后,似乎很难处理导航和主页按钮。我遇到以下问题。

  • 管理左上角的汉堡/后退按钮。将图标和功能切换到菜单和返回导航。
    • 页面标题 - 每当推送和弹出片段时更改页面标题。

我尝试了一些事情,比如重写onBackPressed(),setHomeAsUpIndicator,手动弹出片段。早些时候我使用ActionBarDrawer切换来处理这个问题,但现在却以某种方式失败了。我检查了谷歌样本,他们似乎在大多数地方使用单独的活动。

任何人都可以指导我如何实现正确的后退导航来处理内部片段和页面标题中的NavigationView,Back按钮?我正在使用 AppCompatActivity android.app.Fragment NavigationView 工具栏

Fragment 1 -> Fragment 2 -> Fragment 3

6 个答案:

答案 0 :(得分:16)

通过对ActivityFragment的某种责任分工来说明要容易得多。

Division of responsibilities for Activity and Fragment 问题1:在左上角管理汉堡/后退按钮。将图标和功能切换到菜单和返回导航。

从图示中,解决方案应该由Activity封装,看起来像这样:

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerLayout mDrawer;
    private ActionBar mActionBar;

    private boolean mToolBarNavigationListenerIsRegistered = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mActionBar = getSupportActionBar();

        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        mDrawer.addDrawerListener(mDrawerToggle);
        mDrawerToggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        // On orientation change savedInstanceState will not be null.
        // Use this to show hamburger or up icon based on fragment back stack.
        if(savedInstanceState != null){
            resolveUpButtonWithFragmentStack();
        } else {
            // You probably want to add your ListFragment here.
        }
    }

    @Override
    public void onBackPressed() {

        if (mDrawer.isDrawerOpen(GravityCompat.START)) {
            mDrawer.closeDrawer(GravityCompat.START);

        } else {
            int backStackCount = getSupportFragmentManager().getBackStackEntryCount();

            if (backStackCount >= 1) {
                getSupportFragmentManager().popBackStack();
                // Change to hamburger icon if at bottom of stack
                if(backStackCount == 1){
                    showUpButton(false);
                }
            } else {
                super.onBackPressed();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;

        } else if (id == android.R.id.home) {
            // Home/Up logic handled by onBackPressed implementation
            onBackPressed();
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        // Navigation drawer item selection logic goes here

        mDrawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void replaceFragment() {
        /**
        * Your fragment replacement logic goes here
        * e.g.
        * FragmentTransaction ft = getFragmentManager().beginTransaction();
        * String tag = "MyFragment";
        * ft.replace(R.id.content, MyFragment.newInstance(tag), tag).addToBackStack(null).commit();
        */

        // The part that changes the hamburger icon to the up icon
        showUpButton(true);
    }

    private void resolveUpButtonWithFragmentStack() {
        showUpButton(getSupportFragmentManager().getBackStackEntryCount() > 0);
    }

    private void showUpButton(boolean show) {
        // To keep states of ActionBar and ActionBarDrawerToggle synchronized,
        // when you enable on one, you disable on the other.
        // And as you may notice, the order for this operation is disable first, then enable - VERY VERY IMPORTANT.
        if(show) {
            // Remove hamburger
            mDrawerToggle.setDrawerIndicatorEnabled(false);
            // Show back button
            mActionBar.setDisplayHomeAsUpEnabled(true);
            // when DrawerToggle is disabled i.e. setDrawerIndicatorEnabled(false), navigation icon
            // clicks are disabled i.e. the UP button will not work.
            // We need to add a listener, as in below, so DrawerToggle will forward
            // click events to this listener.
            if(!mToolBarNavigationListenerIsRegistered) {
                mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onBackPressed();
                    }
                });

                mToolBarNavigationListenerIsRegistered = true;
            }

        } else {
            // Remove back button
            mActionBar.setDisplayHomeAsUpEnabled(false);
            // Show hamburger
            mDrawerToggle.setDrawerIndicatorEnabled(true);
            // Remove the/any drawer toggle listener 
            mDrawerToggle.setToolbarNavigationClickListener(null);
            mToolBarNavigationListenerIsRegistered = false;
        }

        // So, one may think "Hmm why not simplify to:
        // .....
        // getSupportActionBar().setDisplayHomeAsUpEnabled(enable);
        // mDrawer.setDrawerIndicatorEnabled(!enable);
        // ......
        // To re-iterate, the order in which you enable and disable views IS important #dontSimplify.
    }
}

问题2:页面标题 - 每当推送和弹出片段时更改页面标题。

基本上,这可以在每个onStart的{​​{1}}中处理,即您的ListFragment,DetailsFragment和CommentsFragment看起来像这样:

Fragment

也可能值得在@Override public void onStart() { super.onStart(); // where mText is the title you want on your toolbar/actionBar getActivity().setTitle(mText); } 片段中使用setRetainInstance(true)

答案 1 :(得分:5)

TL;博士

观看: https://youtu.be/ANpBWIT3vlU

克隆这个: https://github.com/shredderskelton/androidtemplate

这是一个非常常见的问题,我通过创建一种模板项目来克服这个问题,每当我启动一个新的Android项目时,我都会使用它。我们的想法是尽可能多地抽象处理后退按钮的逻辑,即汉堡包'指标和片段管理成可重用的类:

首先创建一个BaseActivity和BaseFragment类。这是您尽可能多地使用可重用代码的地方。

让我们从您的BaseActivity开始

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    fragmentManager = getSupportFragmentManager();
    fragmentHandler = new AddFragmentHandler(fragmentManager);
    fragmentManager.addOnBackStackChangedListener(backStackListener);
}

FragmentManager是拥有后台堆栈的关键,因此您需要从此处监听后台堆栈的更改。 AddFramentHandler是我编写的一个小类,可以更容易地从Fragments中添加Fragments。稍后会详细介绍。

@Override
public void onBackPressed() {
    if (sendBackPressToDrawer()) {
        //the drawer consumed the backpress
        return;
    }

    if (sendBackPressToFragmentOnTop()) {
        // fragment on top consumed the back press
        return;
    }

    //let the android system handle the back press, usually by popping the fragment
    super.onBackPressed();

    //close the activity if back is pressed on the root fragment
    if (fragmentManager.getBackStackEntryCount() == 0) {
        finish();
    }
}

onBackPressed是大多数魔法发生的地方。您会注意到方法的纯文本格式。我是一个巨大的Clean Code粉丝 - 如果您需要撰写评论,那么您的代码就不干净了。基本上你需要真正有一个中心位置,当你不确定为什么没有按照你期望的方式按下按钮时,你可以跑到哪里。这个方法就是那个地方。

private void syncDrawerToggleState() {
    ActionBarDrawerToggle drawerToggle = getDrawerToggle();
    if (getDrawerToggle() == null) {
        return;
    }
    if (fragmentManager.getBackStackEntryCount() > 1) {
        drawerToggle.setDrawerIndicatorEnabled(false);
        drawerToggle.setToolbarNavigationClickListener(navigationBackPressListener); //pop backstack
    } else {
        drawerToggle.setDrawerIndicatorEnabled(true);
        drawerToggle.setToolbarNavigationClickListener(drawerToggle.getToolbarNavigationClickListener()); //open nav menu drawer
    }
}

这是BaseActivity的另一个关键部分。基本上,此方法检查您是否位于根片段并相应地设置指示符。请注意,它会根据后端堆栈中的碎片数来更改侦听器。

然后是BaseFragment:

@Override
public void onResume() {
    super.onResume();
    getActivity().setTitle(getTitle());
}

protected abstract String getTitle();

上面的代码显示了片段如何处理标题。

答案 2 :(得分:1)

"页面标题 - 每当推送和弹出片段时更改页面标题"

删除片段时,方法为isRemoving()。它有助于改变标题。

@Override
public void onStop() {
    super.onStop();
    if (isRemoving()) {
        // Change your title here
    }
}

"功能菜单和返回导航"

建议:我们必须依赖默认的android导航系统。如果我们将addToBackStack()用于我们的片段,理论上我们根本不必覆盖onBackPressed()。

  1. "应用程序不会重新定义系统图标的预期功能(例如“后退”按钮)。"
  2. "应用程序支持标准系统后退按钮导航,不使用任何自定义,屏幕上的"后退按钮"提示"
  3. 核心应用质量:https://developer.android.com/distribute/essentials/quality/core.html

    "在左上角管理汉堡/后退按钮"

    我建议使用活动而不是' MainActivityDetailFragment'避免并发症。

答案 3 :(得分:1)

尝试这样的事情:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    if (getSupportActionBar()!=null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    final ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(drawerToggle);
    drawerToggle.syncState();

    final View.OnClickListener originalToolbarListener = drawerToggle.getToolbarNavigationClickListener();

    final View.OnClickListener navigationBackPressListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getFragmentManager().popBackStack();
        }
    };

    getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            if (getFragmentManager().getBackStackEntryCount() > 0) {
                drawerToggle.setDrawerIndicatorEnabled(false);
                drawerToggle.setToolbarNavigationClickListener(navigationBackPressListener);
            } else {
                drawerToggle.setDrawerIndicatorEnabled(true);
                drawerToggle.setToolbarNavigationClickListener(originalToolbarListener);
            }
        }
    });

    // Though below steps are not related but I have included to show drawer close on Navigation Item click. 

    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {
            int id = item.getItemId();
            /**
             * handle item clicks using id
             */
            drawer.closeDrawer(GravityCompat.START);
            return true;
        }
    });
}

处理抽屉状态onBackPressed

@Override
public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

要重新加载之前的fragment,请始终将片段事务添加到后栈,如下所示:

FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
SomeFragment fragmentToBeLoaded = new SomeFragment();
fragmentTransaction.replace(R.id.fragment_container, fragmentToBeLoaded,
                fragmentToBeLoaded.getName());
fragmentTransaction.addToBackStack(fragmentToBeLoaded.getName());
fragmentTransaction.commit();

要动态更改页面标题,您可以通过Fragment onStartonResume方法调用此方法:

@Override
public void onStart() {
   super.onStart();
   getActivity().setTitle("Title for fragment");
}

注意:我考虑过标准布局声明,因此我没有包含任何布局。

答案 4 :(得分:0)

在您调用Fragments的MainActivity中添加此项。 getBackStackEntryCount()返回后栈中的片段数。堆栈底部的片段具有索引0的位置。popBackStack()从后台堆栈中弹出顶部片段

But sometimes you do need to set those values

在你要回去的片段中使用此功能

[http]
    postbuffer = 524288000
[pack]
    threads = 1
    deltaCacheSize = 1024m
    packSizeLimit = 1024m
    windowMemory = 1024m
[core]
    packedGitLimit = 1024m
    packedGitWindowSize = 1024m

答案 5 :(得分:0)

好的,经过大量的测试后,我终于成功设置了一个好的导航。我需要和你完全一样,唯一的区别是我使用的是v4 Fragments,但我认为这不会改变任何东西。

我没有使用ActionBarDrawerToggle,因为Google的最新示例不再使用此组件。

以下解决方案也适用于深度导航:父级活动 - >片段 - >片段等。

片段中唯一需要改变的是标题:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    getActivity().setTitle(R.string.targets);
}

在父Activity onCreate方法中,我初始化以下内容:

    mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
    setupDrawerContent(mNavigationView);

    final Toolbar toolbar = (Toolbar) findViewById(R.id.drawer_toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_24);// Set the hamburger icon
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);// Set home button pressable

    // Handle the changes on the actionbar
    getSupportFragmentManager().addOnBackStackChangedListener(
            new FragmentManager.OnBackStackChangedListener() {
                public void onBackStackChanged() {
                    // When no more fragments to remove, we display back the hamburger icon and the original activity title
                    if (getSupportFragmentManager().getBackStackEntryCount() <= 0) {
                        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_24);
                        setTitle(R.string.app_name);
                    }
                    // Else displays the back arrow
                    else {
                        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_back_24);
                    }
                }
            });

现在是处理Home按钮上的操作的代码:

@Override
public boolean onOptionsItemSelected(MenuItem item){
    // Close the soft keyboard right away
    Tools.setSoftKeyboardVisible(mViewPager, false);

    switch (item.getItemId()) {
        case android.R.id.home:

            // When no more fragments to remove, open the navigation drawer
            if (getSupportFragmentManager().getBackStackEntryCount() <= 0) {
                mDrawerLayout.openDrawer(GravityCompat.START);
            }
            // Removes the latest fragment
            else {
                getSupportFragmentManager().popBackStack();
            }

            return true;
    }
    return super.onOptionsItemSelected(item);
}

最后处理背压动作的代码:

@Override
public void onBackPressed() {
    // When no more fragments to remove, closes the activity
    if (getSupportFragmentManager().getBackStackEntryCount() <= 0) {
        super.onBackPressed();
    }
    // Else removes the latest fragment
    else {
        getSupportFragmentManager().popBackStack();
    }
}

注意:我使用的是AppCompatActivityNavigationView和主题Theme.AppCompat.Light.NoActionBar