简体   繁体   中英

Add Icon to the left of the title in the action bar in android

I want to add a clickable icon/button to the left of the title in the action bar . How to do it? Following is the code with which I have added search and setting icon to the action bar. They appear on the right. But i want to add a new icon to the left of title. How to do it? 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"
    />

MAIN ACTIVITY

     @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;
    }

You can show an icon at the left side using the following code.

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

But it wont be clickable. To make a clickable icon at the left, you need to use Toolbar instead of an action bar.

You can do the following:

1- create your file_name.xml then Add Toolbar .

2- add RelativeLayout inside the Toolbar 's tag.

3- add your views ie( ImageButton , TextView ,...)

Note: The TextView you are adding is the title of Toolbar .

Sample Code: 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>

Output:

看到

Recommended way

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

Handle icon click event

@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);

    }
}

One thing is that by default title and app icon set into the left and other than icons sent into the right side. If you want to add your icons into the left side there is a way to them into to left side which is:

step 1. create a custom layout which having search, setting icon and your title as you want.

step 2. create a toolBar layout like:

<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"/>

step 3. inflate your custom layout into the toolbar like:

@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);
}

You can replace default navigation icon (and button of cause) in following way.

Define usual UI with toolbar in your XML:

<?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>

Then setup your Toolbar as ActionBar in onCreate method

@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
}

Handle back navigation button in onOptionsItemSelected method:

@Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        if (menuItem.getItemId() == android.R.id.home) {

            // Do whatever you want

            return true;
        }

        return super.onOptionsItemSelected(menuItem);
    }

The same in 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()
    }
}

Result: Android工具栏在标题前添加图标

As this is updated era of Android, You must go for Toolbar so that you can do any kind of customization with the help of xml. Instead of using menu i would suggest to use toolbar

<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>

And through code you can handle event

I always like to put a AppBarLayout that I can control the way the toolbar appears

<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 way a can put more elements and arrange them like I want. In this case insert a left icon to close the activity by a fragment.

So in the fragment a do this

 //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!!
}

The result will be something like this:

在此输入图像描述

The action "SALVAR" i put via inflat menu

 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)
        }

    }

Menu XML layout 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>

And do not forget to use setHasOptionsMenu(true) to enable the menu.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM