Android – Material Design Tutorial : 10 ( Password visibility toggle )

Password Visibility Toggle:

Recently , Android support library 24.2.0 is released and  “Password Visibility Toggle “ is introduced.
Check “API Updates” tab here for 24.2.0

What is Password Visibility Toggle :

Using this icon, we can enable and disable password visibility in a password input field.

When the visibility icon is displayed with a text field, it indicates whether or not that field’s input is visible. The text field’s visibility may be toggled on or off using the icon:

  • Visibility enabled: Icon opacity at 54%, with the password visible
  • Visibility disabled: Icon opacity at 38%, with the password represented by midline ellipses
How it was before ?
normal_android_password_visibility_toggle

How it is now ?

 current_android_password_visibility_toggle

How to include Password Visibility Toggle ?

  1. Create one simple Application on Android Studio with one Activity as “MainActivity.java” with its layout as “activity_main.xml
  2. Update your “dependencies” tab as below :
dependencies {
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.android.support:design:24.2.0'
}
  1. Create one login Screen : Update your activity_main.xml as
<?xml version="1.0" encoding="utf-8"?>
<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:background="@color/colorBack"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/layout_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColorHint="@color/colorHint">

        <EditText
            android:id="@+id/editTextEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_email"
            android:inputType="textEmailAddress"
            android:textColor="@color/textColor" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/layout_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/layout_email"
        android:textColorHint="@color/colorHint">

        <EditText
            android:id="@+id/editTextPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="45dp"
            android:hint="@string/hint_password"
            android:inputType="textPassword"
            android:textColor="@color/textColor" />
    </android.support.design.widget.TextInputLayout>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/layout_email"
        android:layout_marginTop="104dp"
        android:background="@color/buttoncolor"
        android:text="Login"
        android:textColor="@color/textColor" />
</RelativeLayout>
  1. Update your colors.xml :
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorBack">#263238</color>
    <color name="buttoncolor">#00838F</color>
    <color name="textColor">#ffffff</color>
    <color name="colorHint">#546E7A</color>
</resources>

Also strings.xml :

<resources>
    <string name="app_name">CustomVisibilityPwd</string>
    <string name="hint_email">Enter Your email</string>
    <string name="hint_password">Enter Password</string>
    <string name="hint_empty">This field cannot be blank</string>
    <string name ="error_email">Please enter a valid email</string>
</resources>
That’s it. Run this application and you will see the changes as the second image above.
More Customization :

Currently , following are the supported attributes we can use ( as defined in the documentation )  :

no attribute meaning
1 android.support.design:passwordToggleContentDescription Text to set as the content description for the password input visibility toggle.
2 android.support.design:passwordToggleDrawable Drawable to use as the password input visibility toggle icon.
3 android.support.design:passwordToggleEnabled Whether the view will display a toggle when the EditText has a password.
4 android.support.design:passwordToggleTint Icon to use for the password input visibility toggleMay be a color value
5 android.support.design:passwordToggleTintMode Blending mode used to apply the background tint.

a) add xmlns to your <RelativeLayout > :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
     ....
     ....
     >

Now update your password field with a different icon and a different icon color :

<android.support.design.widget.TextInputLayout
    android:id="@+id/layout_password"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/layout_email"
    android:textColorHint="@color/colorHint"
    app:passwordToggleEnabled = "true"
    app:passwordToggleTint="@color/colorHint"
    app:passwordToggleDrawable="@drawable/ic_android_white_18dp">

 Output will be like the second gif above with a different icon and color .

You can check this project on Github.

Don’t forget like our facebook page, Share and subscribe for weekly new articles ?

Testing in Android : Part 3 : Using Mockito

By default , local unit tests are executed against a modified version of android.jar library. This library does not contain any actual code. So, if we make any call to android classes, it will throw an exception. We can use Mocking Framework mockito to mock objects and define outputs of certain method calls.

Mockito is an open sourced testing framework for Java that allows to create mock objects in Automated unit Tests.In this example, we will “mock” “MainActivity” class.

Steps to use Mockito Framework :
  1. include mockito library dependency in your build.gradle :

    testCompile "org.mockito:mockito-core:1.9.5"
  2. Add  @RunWith(MockitoJUnitRunner.class) before unit test class name
  3. To create any mocked object of Android Dependency, use @Mock before that object name

    @Mock
    Context mMockedContext;

    Or you can use static method mock() to mock any class :

    MainActivity activity = Mockito.mock(MainActivity.class);
  4. use when().thenReturn() to use a condition and return value for it.

    @Test
    public void test_when_thenReturn(){
    MainActivity activity = Mockito.mock(MainActivity.class);
    when(activity.getName()).thenReturn("MainActivity");
    assertThat(activity.getName(),is("MainActivity"));
    }
  5. use verify() to detect if any conditioned are met or not like if a method is called with a certain parameter, if it was called once or twice etc

    public void test_verify(){
        MainActivity activity = Mockito.mock(MainActivity.class);
    
        when(activity.getName()).thenReturn("MainActivity");
        when(activity.getNumber(anyInt())).thenReturn(0);
    
        //verify if getName() is never called
        verify(activity,never()).getName();
    
        //now call it one time
        activity.getName();
    
        //verify if it is called once
        verify(activity,atLeastOnce()).getName();
    
        //call getNumber method with a parameter
        activity.getNumber(1);
    
        //verify if getNumber was called with parameter 1
        verify(activity).getNumber(1);
    }

    similarly we can use atLeast(int param),times(int param),atMost(int) etc. with verify

  6. we can use spy() of a real object. It will call the real method of that object.

    public void test_spy(){
    List list = new LinkedList();
    List spyList = spy(list);when(spyList.size()).thenReturn(200);assertThat(spyList.size(),is(200));
    }

That’s it. Clone this project from GitHub and try it by yourself.

Testing in Android : Part 2 : Using Hamcrest

How to create a simple Unit Test :  
  1. Open the application we have used in our last tutorial, create one new class “AdditionTest.java” and add the following method :

    @Test
    public void addition_isCorrect() throws Exception {
        assertEquals(4, 2 + 2);
    }

    @Testis used to indicate that this method is a unit test method

  2. Now right click on the method and click on “Run “addition_isCorrect()”

  3. One bottom window will be open inside “Android Studio” and you can see that the test result . If everything goes fine, you will see your test method name with a green button as “OK”
    .android unitTesting
  4. You can add new test methods inside this class or you can add multiple test classes.
Using Hamcrest :
Hamcrest framework is used for checking conditions in code via existing matchers classes . assertThat  statement is used followed by different matchers in JUnit.

JUnit4 :

assertEquals(expected,actual)

Hamcrest :

assertThat(actual,equalTo(expected))
assertThat(actual,is(expected))
assertThat(actual,is(equalTo(expected)))

How to use Hamcrest :

To use Hamcrest in Android Studio, include the following in dependencies tab of your build.gradle file

testCompile 'org.hamcrest:hamcrest-library:1.3'

Sync your project and modify the addition_isCorrect() method of AdditionTest class as below : 

@Test
public void addition_isCorrect() throws Exception {
    assertEquals(4, 2 + 2);

    assertThat(2+2,is(4));
    assertThat(2+2,equalTo(4));
    assertThat(2+2,is(equalTo(4)));
}

Don’t forget to import the following :

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
Run your test  , and you can see that all tests will execute as before.
This project is shared on Github . You can pull it from here.
Check here  for more tutorials on Hamcrest.