How can an activity use a Toolbar without extending AppCompatActivity

前端 未结 2 1805
别那么骄傲
别那么骄傲 2021-01-20 06:05

I have an activity HomeView which already extends another activity and it cannot extend AppCompatActivity. But HomeView needs to have a Toolbar. Th

2条回答
  •  广开言路
    2021-01-20 06:23

    Actually, it is pretty simple:

    public class YourActivity extends SomeActivity implements AppCompatCallback {
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        // create the delegate
        delegate = AppCompatDelegate.create(this, this);
        delegate.onCreate(savedInstanceState);
        delegate.setContentView(R.layout.activity_details);
    
        // add the Toolbar
        Toolbar toolbar= (Toolbar) findViewById(R.id.toolbar);
        delegate.setSupportActionBar(toolbar);
      }
    
      @Override
      public void onSupportActionModeStarted(ActionMode mode) {
        // leave it empty
      }
    
      @Override
      public void onSupportActionModeFinished(ActionMode mode) {
        // leave it empty
      }
    
      @Nullable
      @Override
      public ActionMode onWindowStartingSupportActionMode(ActionMode.Callback callback) {
        return null;
      }
    

    That's it. Please, don't forget to set a AppTheme.NoActionBar theme to YourActivity in the AndroidManifest.xml.

提交回复
热议问题