Display back button on action bar

2020-01-23 15:10发布

I'm trying to display a Back button on the Action bar to move previous page/activity or to the main page (first opening). And I can not do it.

my code.

ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);

the code is in onCreate.

22条回答
该账号已被封号
2楼-- · 2020-01-23 15:54

It could be too late to answer but I have a shorter and more functional solution in my opinion.

// Inside your onCreate method, add these.
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);

// After the method's closing bracket, add the following method exactly as it is and voiulla, a fully functional back arrow appears at the action bar
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    onBackPressed();
    return true;
}
查看更多
太酷不给撩
3楼-- · 2020-01-23 15:56

This is simple and works for me very well

add this inside onCreate() method

getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

add this outside oncreate() method

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    onBackPressed();
    return true;
}
查看更多
ら.Afraid
4楼-- · 2020-01-23 15:58

Try this, In your onCreate()

 getActionBar().setHomeButtonEnabled(true);
 getActionBar().setDisplayHomeAsUpEnabled(true);

And for clickevent,

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; goto parent activity.
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
查看更多
小情绪 Triste *
5楼-- · 2020-01-23 15:59

Add below code in the onCreate function:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

And then override: @Override public boolean onOptionsItemSelected(MenuItem item){ onBackPressed(); return true; }

查看更多
登录 后发表回答