Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action Bar's onClick listener for the Home button

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.

like image 736
noloman Avatar asked Jun 18 '12 09:06

noloman


People also ask

What is an onClick 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.

How do I set click listener?

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.

How do I get the action bar?

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.


2 Answers

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); } 
like image 163
Saad Mahmud Avatar answered Oct 13 '22 06:10

Saad Mahmud


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

like image 40
lynn8570 Avatar answered Oct 13 '22 06:10

lynn8570