完全在代码中创建和配置 Android 工具栏

Create and configure an Android Toolbar fully in code

我需要在 activity 中动态创建一个工具栏。由于设计原因,我无法在 AXML 中创建它,必须完全以编程方式创建它。遗憾的是,大多数高级设计属性没有编码等效项。

如何完全用代码配置工具栏以匹配以下 AXML?请注意,我使用的是 Support.V7.Widget.Toolbar 以便我的应用向后兼容 Android 5.0.

 <android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
   android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    />

方法一:先创建再配置

我当前的代码:

var toolbar = new Toolbar(this);
toolbar.Title = "View Options";

// the following properties exist but are only GETTERS! .. how do I change them?
toolbar.Width = "parent_width";
toolbar.Height = "wrap_content";

// the following properties don't exist.. what do I do?
toolbar.MinHeight = "?aatr/actionBarSize";
toolbar.Background = "?attr/colorPrimary";
toolbar.Theme = "@style/ThemeOverlay.AppCompat.Dark.ActionBar";
toolbar.PopupTheme = "@style/ThemeOverlay.AppCompat.Light";

方法 2:使用属性

或者,我可以在构建时将 "attributes" 传递给工具栏,但是无法 "create" 和 IAttributeSet 或在集合中更改属性!

我需要创建下图中的 PINK 工具栏:

编辑: 抱歉,我的问题与 this 不同,后者只是关于创建视图。我需要在具有更多属性的视图中创建工具栏。

首先要做的是在styles.xml

中为工具栏创建样式
<style name="toolbarTheme" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
        <item name="android:background">#ff4081</item>
        <item name="android:paddingLeft">16dp</item>
</style>

那你得在attrs.xml

里面加个引用
<resources>
    <attr name="toolbarTheme" format="reference"/>
</resources>

然后在你的应用程序主题中,你必须 link 具有内部样式的属性 styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="@attr/toolbarTheme">@style/toolbarTheme</item>
</style>

让我们创建工具栏

// specify theme [ specify theme in attrs.xml ]
Toolbar toolbar = new Toolbar(this,null,R.attr.toolbarTheme);
// first params => width
// second params => Height
Toolbar.LayoutParams params = new Toolbar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                150);
toolbar.setLayoutParams(params);

// reference to root view ( RelativeLayout )
RelativeLayout view = (RelativeLayout) findViewById(R.id.activity_main);
// add the toolbar
view.addView(toolbar, 0); // 0 means the top you should change it.

您可以使用方法 setPopupTheme()

设置 popupTheme

您可以使用 setBackgroundColor()

方法设置背景颜色