Animated Gradient Background [Instagram App Login Screen]

I’m sure that you’ve seen the Instagram App’s login screen. Its background and the complete theme are really great. Therefore, I want to make one for myself :P
Firstly, if you do not want to read the whole description, you can check the complete example application via my GitHub project.

Github Gradient Linear Android Example


Okay, let’s first talk about very simple but elegant background animation.
First of all, we need some colour XML;

Color XML :

Can you feel the love tonight :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#4568DC"
        android:endColor="#B06AB3"
        android:angle="135"/>
</shape>

Pacific Dream :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#34e89e"
        android:endColor="#0f3443"
        android:angle="90"/>
</shape>

The Blue Lagoon :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#43C6AC"
        android:endColor="#191654"
        android:angle="135"/>
</shape>

Venice :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#6190E8"
        android:endColor="#be7bf9"
        android:angle="45"/>
</shape>
These are our gradient colours :)

Animation List XML

Now, we need an animation_list XML to use these colours.
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/pacific_dream"
        android:duration="10000" />
    <item
        android:drawable="@drawable/venice"
        android:duration="10000" />
    <item
        android:drawable="@drawable/love_and_liberty"
        android:duration="10000" />

    <item
        android:drawable="@drawable/can_you_feel_the_love_tonight"
        android:duration="10000" />

    <item
        android:drawable="@drawable/honey_dew"
        android:duration="10000" />
    <item
        android:drawable="@drawable/the_blue_lagoon"
        android:duration="10000" />
</animation-list>
<animation-list></animation-list> use these items(colors) to make a perfect gradient animation transition.
Do not forget to add your animation_list background to your layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/animation_list"
    android:orientation="vertical">
    
</LinearLayout>

Let’s Change Our Gradient Background

This part is in our Activity. We just create an AnimationDrawable object and set it by our layout’s background. Hence, it can use to start the transition.
setEnterFadeDuration is equal to FadeIn
setExitFadeDuration is equal to FadeOut
We must set millisecond for these durations.
LinearLayout container;
AnimationDrawable anim;

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

    container = (LinearLayout) findViewById(R.id.container);

    anim = (AnimationDrawable) container.getBackground();
    anim.setEnterFadeDuration(6000);
    anim.setExitFadeDuration(2000);
}


@Override
protected void onResume() {
    super.onResume();
    if (anim != null && !anim.isRunning())
        anim.start();
}

@Override
protected void onPause() {
    super.onPause();
    if (anim != null && anim.isRunning())
        anim.stop();
}
Do not forget to onResume and onPause part or this transition will consume the real device.
Ta-daaa :) Finally we make an animated gradient background :)
If you have any question, ask me :)

How to Fix Exception java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider

Hey,
If you’re using Firebase Cloud Messaging (FCM) and your minimum API level is 19, you will face this exception in 4.4.2 +.

Step 1 : Dependencies

First of all, we need to add to our build. Gradle file
// Multidex
compile 'com.android.support:multidex:1.0.1'

Step 2: MultiDexEnabled

Add multiDexEnabled true in our build.gradle’s android part
defaultConfig {
    multiDexEnabled true
}

Step 3: BaseApplication Part

Override attachBaseContext function and install our MultiDex
public class BaseApplication extends Application {
    
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

}
Important Note: DO NOT forget to install MultiDex in attachBaseContext!
After all these parts are done, you’re good to go!
If you have any question, ask me :)

How to Fix Exception Error: BinderProxy@45d459c0 is not valid

Hey,
If you’re facing this error, you probably trying to show a dialog after execution of a background thread, while your Activity is about destroying.
Fortunately, we can fix this error easily.

if(!((Activity) context).isFinishing())
{
// Your progress dialog is here
}
Just an “if” solution fixed this error. Its logic is so simple, if your activity is not destroying, then show your progress dialog.
So simple right? :)
If you have any question, ask me :)

How to get build/version number?

Hey,
If you need to get or control your application’s build/version number. You access them easily.
Java:
try {
    PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    version = pInfo.versionName;
    int versionCode = pInfo.versionCode;
    Log.d("MyApp", "Version Name : "+version + "\n Version Code : "+versionCode);
} catch(PackageManager.NameNotFoundException e) {
    e.printStackTrace();
    Log.d("MyApp", "PackageManager Catch : "+e.toString());
}

Markdown:
try {
    PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    version = pInfo.versionName;
    int versionCode = pInfo.versionCode;
    Log.d("MyApp", "Version Name : "+version + "\n Version Code : "+versionCode);
} catch(PackageManager.NameNotFoundException e) {
    e.printStackTrace();
    Log.d("MyApp", "PackageManager Catch : "+e.toString());
}
PackageInfo class let you access build and version number. As you can see pInfo.versionName will get you the full version and pInfo.versionCode will get you just the version code.
So simple, so easily :)
If you have any question, ask me :)

How to bring a view to the front [ Especially for Custom Loading Indicator ]

Hey,
Z-Indexing is kinda confusing in Android. ( Thank you Google :P ) Especially if you want to use a custom loading indicator and your other views just pop-up front of your loading indicator. That could be very annoying.
Fortunately, the solution is extremely easy ( IDK but I could not find this basic solution easily ). Just one single method will let you bring your view to the front and the magic words are :
myView.bringToFront();
.bringToFront()” method will let you a perfect indicator view :)
Also, there is another option to use parent-children relationship views.
bringChildToFront(View child);
bringChildToFront(View child)” will let you to z-index which child do you want to use :)
That’s it :)
If you have any question, ask me :)

How to detect orientation change and get the current orientation?

Orientation changes are not that good for applications but sometimes this is inevitable and this little method helps us :)
onConfigurationChanged method let us detect orientation changes and we can get current orientation with Configuration.ORIENTATION_LANDSCAPE or ORIENTATION_PORTRAIT. Just one if-else statement and ta-daaa :) Just put your logic in here and you’re ready to go!

Orientation Changes :

Markdown:
@Override
public void onConfigurationChanged(Configuration newConfig) {
 super.onConfigurationChanged(newConfig);
    checkOrientation(newConfig);
}
 
private void checkOrientation(Configuration newConfig){
 // Checks the orientation of the screen
 if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
     Log.d("OrientationMyApp", "Current Orientation : Landscape");
     // Your magic here for landscape mode
 } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
     Log.d("OrientationMyApp", "Current Orientation : Portrait");
     // Your magic here for portrait mode
 }
}


Gist:
java
@Override
public void onConfigurationChanged(Configuration newConfig) {
 super.onConfigurationChanged(newConfig);
    checkOrientation(newConfig);
}
 
private void checkOrientation(Configuration newConfig){
 // Checks the orientation of the screen
 if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
     Log.d("OrientationMyApp", "Current Orientation : Landscape");
     // Your magic here for landscape mode
 } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
     Log.d("OrientationMyApp", "Current Orientation : Portrait");
     // Your magic here for portrait mode
 }
}


Get Orientation Any Time :

public String getScreenOrientation(Context context){
    final int screenOrientation = ((WindowManager)  context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();
    switch (screenOrientation) {
        case Surface.ROTATION_0:
        return "SCREEN_ORIENTATION_PORTRAIT";
        case Surface.ROTATION_90:
        return "SCREEN_ORIENTATION_LANDSCAPE";
        case Surface.ROTATION_180:
        return "SCREEN_ORIENTATION_REVERSE_PORTRAIT";
        default:
        return "SCREEN_ORIENTATION_REVERSE_LANDSCAPE";
    }}
fun getScreenOrientation(context: Context): String {
    val screenOrientation = (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay.orientation
    when (screenOrientation) {
        Surface.ROTATION_0 -> return "SCREEN_ORIENTATION_PORTRAIT"
        Surface.ROTATION_90 -> return "SCREEN_ORIENTATION_LANDSCAPE"
        Surface.ROTATION_180 -> return "SCREEN_ORIENTATION_REVERSE_PORTRAIT"
        else -> return "SCREEN_ORIENTATION_REVERSE_LANDSCAPE"
    }
}

Manifest:

<activity
    android:name=".base.activities.MainActivity"
    android:configChanges="keyboardHidden|orientation|screenSize"
    android:label="@string/app_name"/>
Also, we need to add:
android:configChanges=”keyboardHidden|orientation|screenSize”
for the orientation change.

How to use TextWatcher for more than one EditText?

Hey,
TextWatcher itself is awesome. It provides us a lot of easiness. However, TextWatcher is a pain ass when we want to use more than one EditText at the same time.

How to?

If you’re unlucky like me, you need to waste hours for solving this issue. Luckily, solution is so simple. We just need to remove the current listener and after we’re done with that EditText, just add the listener again.
First we simply create a textWatcher. There are two important points in here.
hashCode() : We use if check hashCode for each EditText because hashCode gives us the which EditText we are using right now.
Add & Remove TextChangedListener : We have to remove and re-add the textChangedListener because after we use setText(), it recalls the listener and it creates a infinite loop. So we simply remove the listener BEFORE what we do with the editText and re-add it when we’re done.
Markdown:
TextWatcher textWatcher = new TextWatcher() {
  @Override
  public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
      
  }

  @Override
  public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

  }

  @Override
  public void afterTextChanged(Editable editable) {
      if (editable != null && !editable.toString().equalsIgnoreCase("")){
          // Checking editable.hashCode() to understand which edittext is using right now
          if (editText1.getText().hashCode() == editable.hashCode()){
              // This is just an example, your magic will be here!
              String value = editable.toString();
              editText1.removeTextChangedListener(textWatcher);
              editText1.setText(value);
              editText1.addTextChangedListener(textWatcher);
          }
      } else if (editText2.getText().hashCode() == editable.hashCode()){
          // This is just an example, your magic will be here!
          String value = editable.toString();
          editText2.removeTextChangedListener(textWatcher);
          editText2.setText(value);
          editText2.addTextChangedListener(textWatcher);
      }
  }
}
Gist:
TextWatcher textWatcher = new TextWatcher() {
  @Override
  public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
      
  }

  @Override
  public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

  }

  @Override
  public void afterTextChanged(Editable editable) {
      if (editable != null && !editable.toString().equalsIgnoreCase("")){
          // Checking editable.hashCode() to understand which edittext is using right now
          if (editText1.getText().hashCode() == editable.hashCode()){
              // This is just an example, your magic will be here!
              String value = editable.toString();
              editText1.removeTextChangedListener(textWatcher);
              editText1.setText(value);
              editText1.addTextChangedListener(textWatcher);
          }
      } else if (editText2.getText().hashCode() == editable.hashCode()){
          // This is just an example, your magic will be here!
          String value = editable.toString();
          editText2.removeTextChangedListener(textWatcher);
          editText2.setText(value);
          editText2.addTextChangedListener(textWatcher);
      }
  }
}
DO NOT FORGET TO ADD TEXTWATCHER LISTENER AT THE BEGINNING !
editText1.addTextChangedListener(textWatcher);
editText2.addTextChangedListener(textWatcher);
Kotlin Markdown:
val textWatcher = object : TextWatcher {
    override
    fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {

    }

    override
    fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {

    }

    override
    fun afterTextChanged(editable: Editable?) {
        if (editable != null && !editable.toString().equals("")) {
            // Checking editable.hashCode() to understand which edittext is using right now
            if (editText.editText!!.text.hashCode() === editable.hashCode()) {
                // This is just an example, your magic will be here!
                val value = editable.toString()
                editText.editText!!.removeTextChangedListener(this)
                editText.editText!!.setText(value)
                editText.editText!!.addTextChangedListener(this)
            }
        } else if (editText2.editText!!.text.hashCode() === editable!!.hashCode()) {
            // This is just an example, your magic will be here!
            val value = editable!!.toString()
            editText2.editText!!.removeTextChangedListener(this)
            editText2.editText!!.setText(value)
            editText2.editText!!.addTextChangedListener(this)
        }
    }
}
Kotlin Gist:
 val textWatcher = object : TextWatcher {
     override
     fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2:Int) {

     } 
 
     override
     fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {

     }
 
     override
     fun afterTextChanged(editable: Editable?) {
         if (editable != null && !editable.toString().equals("")) {
             // Checking editable.hashCode() to understand which edittext is using right now
             if (editText.editText!!.text.hashCode() === editable.hashCode()) {
                 // This is just an example, your magic will be here!
                 val value = editable.toString()
                 editText.editText!!.removeTextChangedListener(this)
                 editText.editText!!.setText(value)
                 editText.editText!!.addTextChangedListener(this)
             }
         } else if (editText2.editText!!.text.hashCode() === editable!!.hashCode()) {
             // This is just an example, your magic will be here!
             val value = editable!!.toString()
             editText2.editText!!.removeTextChangedListener(this)
             editText2.editText!!.setText(value)
             editText2.editText!!.addTextChangedListener(this)
         }
     }
}

How to divide two equal parts in design?

Hey,
Working with XML design can be pain in the ass. This little code segment will let you divide two equal parts.
Divided Two Equal Parts
Markdown :
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:baselineAligned="false">
    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1">
   </RelativeLayout>
   <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1">
   </RelativeLayout>
</LinearLayout>
Gist :
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:baselineAligned="false">
    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1">
   </RelativeLayout>
   <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1">
   </RelativeLayout>
</LinearLayout>

How to place cursor position at the EditText?

Hey,
Sometimes EditText’s cursor has really stupid attitude and we need to make a static position for itself :)

Starting Point :

EditText editText = findViewById(R.id.editText);
editText.setSelection(0); // Starting point Cursor

End Point :

EditText editText = findViewById(R.id.editText);
editText.setSelection(editText.getText().length()); // End point Cursor

Custom Point :

EditText editText = findViewById(R.id.editText);
editText.setSelection(3); // Custom point Cursor
.setSelection() let us where we want to put the cursor.
If you have any question, ask me :)

How to extract filename from Uri?

Now, we can extract filename with and without extension :) You will convert your bitmap to uri and get the real path of your file. Now w...