I'm using Toolbar from Appcompat 21 instead of standard actionbar, everything goes smoothly except that the HomeAsUp Button in an extra activity has no effect.
When I open the PrefsActivity
(code snippets below), the HomeAsUp button shows normally (a small left arrow), When I click the button, from the code, I want it "finish", but it just remains no change. When I add the onCreateOptionsMenu
function to BaseActivity
and inflate the global.xml which only has one menu entry Settings, the click acts as expected, but an extra action menu overflow including the Settings appears, which I don't want. Then I tried to edit the global.xml, deleting the default Settings menu entry, the results is that the button gives no change again.
When testing on an 4.4.2 device with the same code, the problem disappeared.
My question is, how to make the HomeAsUp button of the PrefsActivity
effect while not adding the menu entry by onCreateOptionsMenu
in BaseActivity
?
Some code segments is as following:
BaseActivity:
public abstract class BaseActivity extends ActionBarActivity {
protected Toolbar mActionBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResource());
mActionBar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mActionBar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
protected abstract int getLayoutResource();
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
case R.id.action_settings:
startActivity(new Intent(this, PrefsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
// add this function, the button acts normally, but an extra
// action overflow menu appears in the right side of the Toolbar
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.global, menu);
return true;
}
//...
}
PrefsActivity.java:
public class PrefsActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(R.id.frag_container, new PrefsFragment())
.commit();
}
@Override
protected int getLayoutResource() {
return R.layout.activity_prefs;
}
}