【问题标题】:Add Icon to the left of the title in the action bar in android在android中的操作栏标题左侧添加图标
【发布时间】:2017-07-31 12:44:49
【问题描述】:

我想在操作栏中的标题左侧添加一个可点击的图标/按钮。怎么做? 以下是我将搜索和设置图标添加到操作栏的代码。它们出现在右侧。但我想在标题左侧添加一个新图标。怎么做? XML:

    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        tools:context=".ui.home.activities.TransactionSearchActivity">

    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        android:title="search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="always" />

    <item android:id="@+id/action_setting"
        android:title="categories"
        android:icon="@drawable/icon_settings_h"
        app:showAsAction="always"
    />

主要活动

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }

【问题讨论】:

    标签: android menu


    【解决方案1】:

    您可以使用以下代码在左侧显示一个图标。

    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | 
    ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_USE_LOGO);
    actionBar.setIcon(R.drawable.ic_launcher);
    

    但它不会是可点击的。要在左侧制作可点击的图标,您需要使用工具栏而不是操作栏。

    【讨论】:

      【解决方案2】:

      由于这是 Android 的更新时代,您必须选择 Toolbar,以便您可以在 xml 的帮助下进行任何类型的自定义。我建议不要使用菜单,而是使用工具栏

      <android.support.v7.widget.Toolbar
          android:id="@+id/toolbar"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_alignParentBottom="true"
          android:background="#ffffa302"
          android:minHeight="@android:dimen/notification_large_icon_height">
      
          <ImageButton
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/imageButton"
              android:layout_gravity="left"
              android:drawable="@drawable/pinterest_pin"
              android:clickable="true"/>
      
      </android.support.v7.widget.Toolbar>
      

      通过代码你可以处理事件

      【讨论】:

      【解决方案3】:

      一件事是默认情况下,标题和应用程序图标设置在左侧,而不是发送到右侧的图标。如果您想将图标添加到左侧,有一种方法可以将它们添加到左侧:

      第 1 步。 创建一个自定义布局,其中包含您想要的搜索、设置图标和标题。

      第 2 步。 创建一个工具栏布局,如:

      <android.support.v7.widget.Toolbar
                      android:id="@+id/toolbar"
                      android:layout_width="match_parent"
                      android:layout_height="?attr/actionBarSize"
                      android:titleTextColor="#ffffff"
                      android:background="#ECA539"
                      app:layout_collapseMode="pin"
                      app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
      

      第 3 步。 将您的自定义布局添加到工具栏中,例如:

      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
      initToolbar();
      
      }
      private void initToolBar() {
      setSupportActionBar(toolbar);
          View customlayout= getLayoutInflater().inflate(R.layout.custom_layout, null);
          toolbar.addView(logo);
      }
      

      【讨论】:

        【解决方案4】:

        您可以执行以下操作:

        1- 创建你的 file_name.xml 然后添加 Toolbar

        2- 在Toolbar 的标签内添加RelativeLayout

        3- 添加您的观点,即(ImageButton,TextView,...)

        注意:你添加的TextViewToolbar的标题。

        示例代码:file_name.xml

        <android.support.v7.widget.Toolbar
                android:id="@+id/products_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/colorPrimaryDark"
                app:layout_collapseMode="pin"
                app:titleTextColor="@android:color/white">
        
                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
        
                    <TextView
                        android:id="@+id/toolbar_title"
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:text="Title"
                        android:gravity="center"
                        android:textColor="@android:color/white"
                        android:textSize="20dp"
                        android:textStyle="bold"
                        android:layout_alignParentStart="true"/>
        
                    <ImageButton
                        android:id="@+id/toolbar_button"
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:src="@drawable/ic_icon_24dp"
                        style="@style/Widget.AppCompat.Button.Borderless"
                        android:layout_alignParentEnd="true"/>
        
                </RelativeLayout>
        </android.support.v7.widget.Toolbar>
        

        输出:

        【讨论】:

        • 最好的解决方案..我尝试了几个..这是最好的。我正在将您的解决方案与 AppBarLayout 一起使用
        • @Muhamoud 感谢您的回答。 file_name.xml 是否需要专门位于某个地方?它需要是菜单布局文件吗?它需要以某种方式膨胀吗?谢谢!
        【解决方案5】:

        我一直喜欢放一个可以控制工具栏出现方式的AppBarLayout

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">
                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbarAddPlan"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:background="?attr/colorPrimary"
                    android:layout_marginLeft="50dp"
                    app:popupTheme="@style/AppTheme.PopupOverlay" >
        
                </android.support.v7.widget.Toolbar>
        
                    <ImageButton
                        android:id="@+id/btnAddPlanTourClose"
                        style="@style/Widget.AppCompat.Button.Borderless"
                        android:layout_width="45dp"
                        android:layout_height="45dp"
                        android:layout_alignParentLeft="true"
                        android:layout_alignParentStart="true"
                        android:layout_centerVertical="true"
                        android:src="@drawable/close_circle_outline" />
                </RelativeLayout>
        </android.support.design.widget.AppBarLayout>
        

        这样可以放置更多元素并按照我的意愿排列它们。在这种情况下,插入一个左图标以通过片段关闭活动。

        所以在片段中这样做

         //That is in the Fragment
        setupToolbar(R.id.toolbarAddPlan,getString(R.string.addPlanTour),true)
        
        
        
        
        
        //It is in na Kotlin Extansion file.
        
        
        
         inline fun Fragment.setupToolbar(@IdRes id: Int, title:String?= null, upNavigation: Boolean = false) : ActionBar {
        
            val activityCompat = activity as AppCompatActivity
            val toolbar = activity?.findViewById<Toolbar>(id)
            activityCompat.setSupportActionBar(toolbar)
            if(title != null){
                activityCompat.supportActionBar?.title = title
            }
            activityCompat.supportActionBar?.setHomeButtonEnabled(true)
            return activityCompat.supportActionBar!!
        }
        

        结果会是这样的:

        我通过膨胀菜单放置的动作“SALVAR”

         override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
                super.onCreateOptionsMenu(menu, inflater)
                inflater?.inflate(R.menu.menu_add_plan_tour,menu)
            }
        
            override fun onOptionsItemSelected(item: MenuItem?): Boolean {
                return when (item?.itemId){
                    R.id.menuPlanTourSave ->{
                        true
                    }else ->return super.onOptionsItemSelected(item)
                }
        
            }
        

        菜单 XML 布局 src/menu/menu_add_plan_tour.xml

            <?xml version="1.0" encoding="utf-8"?>
        <menu xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto">
            <!-- "Mark Favorite", should appear as action button if possible -->
            <item
                android:id="@+id/menuPlanTourSave"
                android:title="@string/btnSave"
                android:tooltipText="@string/btnSave"
                android:contentDescription="@string/btnSave"
                app:showAsAction="always|withText">
                <TextView
                    android:text="@string/btnSave"
                    android:textSize="15dp"
                    android:textColor="@color/colorPrimaryLight"
                    />
        
        
            </item>
        </menu>
        

        不要忘记使用 setHasOptionsMenu(true) 来启用菜单。

        【讨论】:

          【解决方案6】:

          您可以通过以下方式替换默认导航图标(和原因按钮)。

          在您的 XML 中使用工具栏定义常用 UI:

          <?xml version="1.0" encoding="utf-8"?>
          <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="vertical">
          
              <android.support.design.widget.AppBarLayout
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content">
          
                  <android.support.v7.widget.Toolbar
                      android:id="@id/toolbar"
                      android:layout_width="match_parent"
                      android:layout_height="?attr/actionBarSize"/>
          
              </android.support.design.widget.AppBarLayout>
          
              <!-- Here goes your UI -->
          
          </LinearLayout>
          

          然后在 onCreate 方法中将 Toolbar 设置为 ActionBar

          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_menu);
          
              Toolbar toolbar = findViewById(R.id.toolbar);
          
              setSupportActionBar(toolbar);
              getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Make toolbar show navigation button (i.e back button with arrow icon)
          
              toolbar.setNavigationIcon(R.drawable.custom_icon); // Replace arrow icon with our custom icon
          }
          

          在 onOptionsItemSelected 方法中处理返回导航按钮:

          @Override
              public boolean onOptionsItemSelected(MenuItem menuItem) {
                  if (menuItem.getItemId() == android.R.id.home) {
          
                      // Do whatever you want
          
                      return true;
                  }
          
                  return super.onOptionsItemSelected(menuItem);
              }
          

          在 Kotlin 中也是如此

          class MainActivity : AppCompatActivity() {
          
              override fun onCreate(savedInstanceState: Bundle?) {
                  super.onCreate(savedInstanceState)
                  setContentView(R.layout.activity_main)
                  setSupportActionBar(toolbar)
          
                  supportActionBar?.setDisplayHomeAsUpEnabled(true) // Important step, we enable button on the left side of the toolbar
          
                  toolbar.navigationIcon = getDrawable(R.drawable.custom_icon) // Here we change default navigation button icon
          
              }
          
              override fun onOptionsItemSelected(item: MenuItem): Boolean {
                  return when (item.itemId) {
                      android.R.id.home -> {
                          doSomething() // Here we can perform any action
                          true
                      }
                      else -> super.onOptionsItemSelected(item)
                  }
              }
          
              private fun doSomething() {
                  Toast.makeText(this, "Hello", Toast.LENGTH_LONG).show()
              }
          }
          

          结果:

          【讨论】:

          • 修复错误:android:id="@id/toolbar" -> android:id="@+id/toolbar"
          【解决方案7】:

          推荐方式

          getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_settings_24dp);// set drawable icon
          getSupportActionBar().setDisplayHomeAsUpEnabled(true);
          

          处理图标点击事件

          @Override
          public boolean onOptionsItemSelected(MenuItem item) {
          
              switch (item.getItemId()) {
                  case android.R.id.home:
                      Toast.makeText(this, "click..!!", Toast.LENGTH_SHORT).show();
                      return true;
                  default:
                      return super.onOptionsItemSelected(item);
          
              }
          }
          

          【讨论】: