Set drawable icon inside ActionBar in android programmatically

How to add and display any custom image icon inside action bar in android app.

In this tutorial we are creating action bar with custom icon which we have uploaded into drawable folder. We are dynamically calling the action bar using setIcon() method. So here is the complete step by step tutorial for Set drawable icon inside ActionBar in android programmatically.

android-project-download-code-button

How to Set drawable icon inside ActionBar in android programmatically.

Note: If you are facing any type of NullPointerException error then ready my this post to solve this error.

Note: Download the demo_icon from below and put inside drawable-hdpi folder.

drawable hdpi folder

Download below icon and copy inside drawable-hdpi folder.

demo_icon
Code for MainActivity.java file.

 package com.setdrawableiconinsideactionbar_android_examples.com;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 ActionBar actionbar = getActionBar();
 
 actionbar.setTitle(" ACTION BAR TITLE");
 
 actionbar.setIcon(R.drawable.demo_icon);
 
 }
}

Code for activity_main.xml layout file.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.setdrawableiconinsideactionbar_android_examples.com.MainActivity" >

 

</RelativeLayout>

Code for AndroidManifest.xml file.

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.setdrawableiconinsideactionbar_android_examples.com"
 android:versionCode="1"
 android:versionName="1.0" >

 <uses-sdk
 android:minSdkVersion="14"
 android:targetSdkVersion="21" />

 <application
 android:allowBackup="true"
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:theme="@android:style/Theme.Holo.Light" >
 <activity
 android:name=".MainActivity"
 android:label="@string/app_name" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />

 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 </application>

</manifest>

Screenshot:

Set drawable icon inside ActionBar in android programmatically

Click here to download Set drawable icon inside ActionBar in android programmatically project with source code.

Leave a Reply

Your email address will not be published. Required fields are marked *