【问题标题】:how to provide proper back navigation with fragment on clicking the home button如何在单击主页按钮时使用片段提供正确的后退导航
【发布时间】:2014-07-23 15:43:24
【问题描述】:

我想在单击操作栏的主页按钮时提供返回导航。 在主机片段中

((MainActivity)this.getActivity()).fragment_Actualités=new Fragment_Actualités();
         fragmentTransaction.replace(R.id.content_frame,((MainActivity)this.getActivity()).fragment_Actualités);
         fragmentTransaction.addToBackStack(null);
         fragmentTransaction.commit();
        ((MainActivity)this.getActivity()).fragmentManager.executePendingTransactions();
        ((MainActivity)this.getActivity()).supportInvalidateOptionsMenu();

在主机活动中

  public boolean onOptionsItemSelected(MenuItem item) {
    // The action bar home/up action should open or close the drawer.
    // ActionBarDrawerToggle will take care of this.
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    // Handle action buttons
    int id=0;
    if(id==item.getItemId()){
         if(id== R.id.home)
        {
            this.onBackPressed();
            return true;}

        }

super.OnBackPressed 工作正常,当我单击返回按钮时,它会按预期返回 我怎样才能让它发挥作用?

【问题讨论】:

    标签: android android-fragments android-actionbar


    【解决方案1】:

    【讨论】:

    • 尝试但它并没有改变什么。谢谢你的建议。
    【解决方案2】:

    尝试改变:

    this.onBackPressed();
    

    到:

    onBackPressed();
    

    如果您还没有这样做,则扩展 FragmentActivity

    【讨论】:

    • 它并没有改变任何改变 this.onBackPressed by onBackPressed 的东西。但是谢谢 :)
    【解决方案3】:

    再次阅读您的代码,我认为发现了问题,您将 0 分配给 id,因此当您与 item.getItemId() 竞争时,始终返回 false。试试这段代码

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            this.onBackPressed();
            return true;
        }
    }
    

    【讨论】:

    • 感谢您的努力 :) 非常友好。我也尝试了您的建议。但它也不起作用。只有设备的后退按钮有效,但是当我点击应用程序的主页按钮时,它不会返回上一页。
    【解决方案4】:

    终于解决了 问题是,我有 2 个 MenuItems,即 Settings 和 Home One's 。 所以如果只写 R.id.Home 是行不通的,但是当改成 android.R.id.Home 就可以了!!! 使用相同的代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多