【问题标题】:How to add ActionBar to an activity which already extends ListActivity?如何将 ActionBar 添加到已经扩展 ListActivity 的活动中?
【发布时间】:2015-04-26 08:20:12
【问题描述】:

我有一个扩展 ListActivity 的活动。
我可以在不扩展ActionBarActivity 的情况下添加ActionBar 吗?

【问题讨论】:

标签: android android-actionbar android-actionbaractivity


【解决方案1】:

您可以使用支持库提供的新AppCompatDelegate 组件。

ActionBar 现已弃用,您应该使用 Toolbar,以符合 Material Design。您可以使用支持库提供的工具栏。

像这样将它添加到您的 xml 布局中:

<android.support.v7.widget.Toolbar

        android:id="@+id/my_awesome_toolbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="56dp"
        android:background="?attr/colorPrimary"

        />

请务必在您的styles.xml 中使用NoActionBar 主题。使用 Material Design 颜色标签。

<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
</style>

然后,像这样在 OnCreate() 中将 AppCompatDelegate 添加到您的 Activity。

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

    AppCompatCallback callback = new AppCompatCallback() {
        @Override
        public void onSupportActionModeStarted(ActionMode actionMode) {
        }

        @Override
        public void onSupportActionModeFinished(ActionMode actionMode) {
        }
    };

    AppCompatDelegate delegate = AppCompatDelegate.create(this,callback);

    delegate.onCreate(savedInstanceState);
    delegate.setContentView(R.layout.activity_main);

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


}

注意:要创建 AppCompatDelegate,您需要传递 Activity 本身和回调,好的做法应该是在 Activity 中实现回调,但出于缩短原因,我在 onCreate() 中创建了一个实例.

【讨论】:

    【解决方案2】:

    在styles.xml中使用holo主题因为只有holo之后才能使用ActionBar

    使用这个:

    <style name="AppTheme" parent="android:Theme.Holo">
    

    【讨论】:

      【解决方案3】:

      您可以使用 工具栏 :将 AppCompat 工具栏添加到您的活动布局中。

      教程(转到ActionBar):http://android-developers.blogspot.fr/2014/10/appcompat-v21-material-design-for-pre.html

      文档https://developer.android.com/reference/android/support/v7/widget/Toolbar.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多