Set Logo and Title in ActionBar Using ToolBar in android

This is code only post for every begginner.
 Add this code in your activity_main.xml file:-

 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        android:elevation="4dp">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            >
			<ImageView
                    android:id="@+id/logo"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:src="@drawable/image"
                    android:scaleType="centerCrop"
                    android:adjustViewBounds="true"
                    />
            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="@string/app_name"
                android:gravity="center_vertical"
                android:textSize="18dp"
                android:textColor="@color/white"
                android:layout_marginLeft="80dp"
                />
        </RelativeLayout>
    </androidx.appcompat.widget.Toolbar>
</RelativeLayout>

And The below code is for your MainActivity.java file.

 
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity{
	ImageView logo;
    TextView title;
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Toolbar tb = findViewById(R.id.my_toolbar);
		setSupportActionBar(tb);
		
		//Here you can set custom Logo and title using code
		logo = findViewById(R.id.logo);
		title = findViewById(R.id.title);
		
    }
	
}

Happy Coding! 
Thanks.

Comments