Search code examples
androidandroid-actionbartoolbar

Android Toolbar with Avatar and Name clickable


I am looking for a way to create a Toolbar likes a lot of apps with name and a photo.

I need to allow touch, if user touchs the area near the name or the image it will change activity.

Example: enter image description here


Solution

  • You just need to put the ImageView and TextView inside your Toolbar, he is just a ViewGroup. For example:

    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="@dimen/abc_action_bar_default_height_material">
    
        <LinearLayout
                android:id="@+id/linearlayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"" >
    
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:contentDescription="@string/your_image_description"
                android:src="@drawable/your_image"/>
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/your_string" />
    
        </LinearLayout>
    
    </android.support.v7.widget.Toolbar>
    

    After that, you can set the click event on your activity:

        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearlayout);
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "teste", Toast.LENGTH_LONG).show();
            }
        });
    

    Run on the emulator to see the result:

    example running on nexus 5

    Hope this helps.