Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Toolbar on each Activity

My app has a toolbar that should be present on every view. Currently, I do the following in my onCreate() method for each Activity I have:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

Does this need to be done in every onCreate() method in every Activity or is there a simpler way? Also, as a side question, how can I implement a "back" feature in the toolbar that takes the user back one action if they click it?

like image 558
user5294977 Avatar asked Nov 30 '22 00:11

user5294977


1 Answers

Create a Base class for Activity

public abstract class BaseActivity extends AppCompatActivity {

  Toolbar toolbar;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(getLayoutResource());
    configureToolbar();
  }

  protected abstract int getLayoutResource();

  private void configureToolbar() {
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
      setSupportActionBar(toolbar);
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        FragmentManager fm = getSupportFragmentManager();
        if (fm != null && fm.getBackStackEntryCount() > 0) {
          fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        } else {
          finish();
        }
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }
}

And in each Activity extends this BaseActivity to get the ToolBar and implementing the back feature.

At last don't forget to include the ToolBar in each activity layout.

Edit:

Override that method getLayoutResource() in each Activity and pass the layout id.

public class MainActivity extends BaseActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  @Override
  public int getLayoutResource() {
    return R.layout.activity_main;
  }
like image 140
Amit Gupta Avatar answered Dec 04 '22 12:12

Amit Gupta