Search code examples
androidandroid-actionbarandroid-homebutton

Add home button to action bar in the last activity


I want to add a home icon on action bar in my last activity, so that the if the user is at last activity, he just click the custom home icon button on last activity and navigates to the main activity.

I created a new menu

 <item
      android:id="@+id/homeico"
      app:showAsAction="always"
      android:icon="@drawable/homeicon"
        android:title="@string/home_title"  />

and added the below code to the last activity but the icon is not there on the action bar, where i am wrong?

public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub

    MenuInflater inflate = getMenuInflater();
    inflate.inflate(R.menu.homemenu, menu);
        return super.onCreateOptionsMenu(menu);
    }

Solution

  • Do as follows in onCreateOptionsMenu(Menu menu) function of activity.

    MenuItem item=menu.add("Title"); //your desired title here
    item.setIcon(R.drawable.icon); //your desired icon here
    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    item.setOnMenuItemClickListener(new OnMenuItemClickListener() {
    
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            // TODO Auto-generated method stub
                return false;
            }
        });
    }