简体   繁体   中英

Android app - Back button

I want to display a back button in the left corner of the action bar and I do not completely know where to make the change in the activity.java to make it visible and functional.

@Override
    protected void onCreate(Bundle savedInstancesState){
        super.onCreate(savedInstancesState);
        setContentView(R.layout.activity_news);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setIcon(R.mipmap.ic_launcher);

This is what I want to display. View Image

you have to enable it by doing

actionBar.setDisplayHomeAsUpEnabled(true);

then if you want it to do something you need to look for the click in the onOptionsItemSelected

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()){
        case android.R.id.home:
            //do something here
            break;
        default:
            break;
    }

Showing it is as simple as putting this under your onCreate method in your Activity:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Then to control that input put this in your Activity:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            //or do what you want
            finish();
            break;
        default:
            break;
    }
    return super.onOptionsItemSelected(item);
}

// activity

    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

// fragments

    mToolbar = (Toolbar) view.findViewById(R.id.toolbar);

    ((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

It may helps some one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM