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

时间:2016-05-27 15:22:57

标签: android android-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支持库。

谢谢, 利安

2 个答案:

答案 0 :(得分:4)

试试以下

第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();
  

通过直接添加和删除LinearLayout中的元素,也可以在不Toolbar的情况下完成此操作。你可以尝试两种方式。

希望它能提供帮助。

答案 1 :(得分:0)

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

purrr::map(variable, ~ data %>%
                      group_by_at(.x) %>%
                      summarise(number = mean(mpg))) %>%
                      set_names(variable) %>%
                      bind_rows(., .id = 'variable')
相关问题