2017-04-22 62 views
0

我对appbar和一个带appbar的fullsecreen对话框片段(该对话框是从活动中调用的)有一个活性。 当按下活动的主页按钮时,我已经设置了一些操作,当按下对话框片段的主页按钮时,它应该关闭对话框。 我注意到两个按钮有相同的id(android.R.id.home)。而且当调用方法“onOptionsItemSelected”时会发生冲突,因为当我按下对话框的home按钮时,它不起作用,但是如果删除活动上的代码部分(如果id == android.R .id.home) 它工作正常,对话框关闭。 我该怎么做?有没有办法来防止这种冲突,也许为主页按钮设置一个不同的ID?活动主页按钮和Dialogfragment主页按钮ID之间的冲突

这是活动

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_logout) { 
      exitApp(); 
      return true; 
     } 

     else if ((id == android.R.id.home) && searchActivated) { 
      drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); 
      toggle.syncState(); 
      searchActivated=false; 
      reload_fragment_data(); 
      return true; 
     } 
     else if ((id == android.R.id.home) && (!searchActivated)) 
     { 
      drawer.openDrawer(GravityCompat.START); // OPEN DRAWER 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 

    } 

的方法,这是dialogfragment

public boolean onOptionsItemSelected(MenuItem item) { 
     int id = item.getItemId(); 

     if (id == R.id.action_next) { 
      pager.setCurrentItem(pager.getCurrentItem() + 1); 
      updateTitle(); 
      return true; 
     } else if (id==R.id.action_previous) 
     { 

      pager.setCurrentItem(pager.getCurrentItem() - 1); 
      updateTitle(); 
      return true; 
     } 

     else if (id == android.R.id.home) { 

      dismiss(); 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

回答

0

你可以申请,并尝试在活动该解决方案的方法。

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(); 

    Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment_container); 
    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_logout) { 
     exitApp(); 
     return true; 
    } 

    else if ((id == android.R.id.home) && searchActivated && !(fragment instanceof DialogFragmentClassName)) { 
     drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); 
     toggle.syncState(); 
     searchActivated=false; 
     reload_fragment_data(); 
     return true; 
    } 
    else if ((id == android.R.id.home) && (!searchActivated)) 
    { 
     drawer.openDrawer(GravityCompat.START); // OPEN DRAWER 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 

}