How can I implement a custom onClickListener
for the Home button of the Action Bar?
I already did a getSupportActionBar().setDisplayHomeAsUpEnabled(true);
and now I want to redirect the user to a certain activity in case the Home button is clicked.
I tried with:
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: item.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent i = new Intent(); i.setClass(BestemmingActivity.this, StartActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); return true; } }); default: return super.onOptionsItemSelected(item); } }
but it never enters in the onMenuItemClick
.
Basically, it's done just like in this link but still it doesn't enter in the listener.
In Android, the OnClickListener() interface has an onClick(View v) method that is called when the view (component) is clicked. The code for a component's functionality is written inside this method, and the listener is set using the setOnClickListener() method.
Link the button from the XML by calling findViewById() method and set the onClick listener by using setOnClickListener() method. setOnClickListener takes an OnClickListener object as the parameter.
You may otherwise add the action bar by calling requestFeature(FEATURE_ACTION_BAR) or by declaring it in a custom theme with the windowActionBar property. Beginning with Android L (API level 21), the action bar may be represented by any Toolbar widget within the application layout.
if anyone else need the solution
@Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); }
I use the actionBarSherlock, after we set supportActionBar.setHomeButtonEnabled(true);
we can override the onMenuItemSelected method:
@Override public boolean onMenuItemSelected(int featureId, MenuItem item) { int itemId = item.getItemId(); switch (itemId) { case android.R.id.home: toggle(); // Toast.makeText(this, "home pressed", Toast.LENGTH_LONG).show(); break; } return true; }
I hope this work for you ~~~ good luck
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With