Wednesday 6 September 2017

Change SatusBar color and ActionBar color in Android

About Example:- Here is the basic example that "How to Change StatusBarColor and ActionBarColor   in Android Application By using Coding"

Basic Requirement:-
1. MainActivity.java  | activity_main.xml
Steps are:-
Step 1: Add a new project and open activity_main.xml and write following code:-
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
 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="com.example.supriyabharti.changestatusbarcolor.MainActivity">

    <TextView
     android:layout_width="wrap_content"    
     android:layout_height="wrap_content"       
     android:text="Hello World!"     
     app:layout_constraintBottom_toBottomOf="parent"       
     app:layout_constraintLeft_toLeftOf="parent"       
     app:layout_constraintRight_toRightOf="parent"    
     app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Step 2:- MainActivity.java

import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class MainActivity extends AppCompatActivity {

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

        //code for changing ActionBar color of an activity       
       getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorAccent)));

        //code for to change statusbar color of an activity.....        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.RED);
        }
    }
}

Output:-

No comments:

Post a Comment