How can an activity use a Toolbar without extending AppCompatActivity

你。 提交于 2020-01-03 20:12:07

问题


I have an activity HomeView which already extends another activity and it cannot extend AppCompatActivity. But HomeView needs to have a Toolbar. The Android documentation says that any activity which needs to have a Toolbar must extend AppCompatActivity.

How can I get around this limitation?


回答1:


You need to implement AppCompatCallback and use AppCompatDelegate. Here's an excellent article about how to use it: https://medium.com/google-developer-experts/how-to-add-toolbar-to-an-activity-which-doesn-t-extend-appcompatactivity-a07c026717b3#.nuyghrgr9 and also check out https://developer.android.com/reference/android/support/v7/app/AppCompatDelegate.html for knowing which methods to delegate.


AppCompatDelegate

This class represents a delegate which you can use to extend AppCompat's support to any Activity.

When using an AppCompatDelegate, you should any methods exposed in it rather than the Activity method of the same name. This applies to:

addContentView(android.view.View, android.view.ViewGroup.LayoutParams)
setContentView(int)
setContentView(android.view.View)
setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
requestWindowFeature(int)
invalidateOptionsMenu()
startSupportActionMode(android.support.v7.view.ActionMode.Callback)
setSupportActionBar(android.support.v7.widget.Toolbar)
getSupportActionBar()
getMenuInflater()

There also some Activity lifecycle methods which should be proxied to the delegate:

onCreate(android.os.Bundle)
onPostCreate(android.os.Bundle)
onConfigurationChanged(android.content.res.Configuration)
setTitle(CharSequence)
onStop()
onDestroy()



回答2:


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.



来源:https://stackoverflow.com/questions/33358046/how-can-an-activity-use-a-toolbar-without-extending-appcompatactivity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!