我在MainActivity中实现了NavigationView。 MainActivity包含Fragment容器。默认HomeFragment位于此容器内。然后我在这个容器中添加另一个Fragment(SecondFragment)。现在汉堡包图标应该更改为返回导航图标(后退箭头图标),单击此图标应该转到上一个片段。但现在单击主页按钮(后退箭头图标)将打开导航抽屉。这是我的MainActivity` 公共类MainActivity扩展了AppCompatActivity {
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
drawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
default:
Toast.makeText(getApplicationContext(), "Nothing", Toast.LENGTH_SHORT).show();
return true;
}
}
});
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,toolbar, R.string.openDrawer, R.string.closeDrawer) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if (id == android.R.id.home) {
return false;
}
return super.onOptionsItemSelected(item);
}}
`
这是我的SecondFragment代码` 公共类SecondFragment扩展Fragment { TextView收件箱;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_fragment, container, false);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setHasOptionsMenu(true);
return v;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
Log.e("backIcon", "backIcon");
return true;
}
return super.onOptionsItemSelected(item);
}}
`
答案 0 :(得分:0)
您可以使用KeyCode处理:
@Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
// handle back button
return true;
}
return false;
}
});
}
OR
您需要获取onOptionsItemSelected项的ID。 所以根据你可以决定回来。