如何以编程方式将元素添加到工具栏

How to programmatically add elements to toolbar

我目前正在制作一个向后支持工具栏的应用程序,因此我有这个文件

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

然后我通过执行以下操作以编程方式将其添加到视图中:

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

但是,我希望能够将自定义视图添加到工具栏中,例如 EditText 和 TextView,而无需将它们硬编码到上面的 toolbar.xml 中。

有什么办法吗?可能值得注意的是,我使用的是 V7 支持库。

谢谢, 利亚姆

试试下面的方法

第 1 步:将 LinearLayout 添加到 xml 文件中的工具栏

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

第 2 步:在代码中获取此 LinearLayout

Toolbar mToolbar = (Toolbar)findViewById(R.id.toolbar_transaction);
LinearLayout layoutToolbar = (LinearLayout)
                  mToolbar.findViewById(R.id.toolbar_item_container);

第 3 步:使用以下代码

添加和删除此 LinearLayout 的视图
layoutToolbar.addView();
layoutToolbar.removeView();

This can be done without LinearLayout also, by directly adding and removing elements from Toolbar. You can try both the ways.

希望对您有所帮助。

如果 xml 中没有工具栏,可以通过编程方式设置自定义视图

    actionBar.setCustomView(R.layout.custom_view);
    View view = actionBar.getCustomView();
    TextView locationTitle = view.findViewById(R.id.tv_custom_toolbar);
    locationTitle.setText("some text");
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    actionBar.setDisplayHomeAsUpEnabled(true);