我可以在工具栏中看到后退按钮,但是当我点击时,没有任何反应。它不会onOptionsItemSelected
但是当我删除ActionBarDrawerToggle
的整个实现时,后退按钮工作正常。我需要在两者之间切换。提前谢谢。
package demo.sample.com.sample.base;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private DrawerLayout mDrawer;
private ActionBarDrawerToggle mDrawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_digi_care);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, mDrawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawer.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
mDrawer.setFocusable(false);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setItemIconTintList(null);
navigationView.setNavigationItemSelectedListener(this);
navigationView.getMenu().getItem(0).setChecked(true);
mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Logger.i(TAG, "onOptionsItemSelected called");
switch (item.getItemId()) {
case android.R.id.home:
Logger.i(TAG, "Back button pressed"); //Never getting called
//onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.map_menu, menu);
return super.onCreateOptionsMenu(menu);
}
}
答案 0 :(得分:3)
如果要在单击切换按钮时触发onOptionsItemSelected()
方法,则需要使用不带ActionBarDrawerToggle
参数的Toolbar
的四参数构造函数。
public ActionBarDrawerToggle(Activity activity,
DrawerLayout drawerLayout,
int openDrawerContentDescRes,
int closeDrawerContentDescRes)
否则,切换将直接处理抽屉打开/关闭。
答案 1 :(得分:2)
我终于找到了解决方案。而是通过DrawerToggle.setToolbarNavigationClickListener
获取工具栏主页按钮,可以通过mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// event when click home button
Log.d("cek", "home selected");
}
});
处理。
{{1}}
感谢@meow meo。来源 - Cannot catch toolbar home button click event