Building a Visual Password Strength Meter in Android: A Simple Guide
Tags: android, password, ui
Published: 2023-06-05 17:16:48

Creating an interactive and user-friendly interface is crucial for ensuring user engagement. One such tool that significantly boosts user experience is a password strength indicator. Today, we're going to break down the creation of a simple yet effective password strength meter implemented in Android using the Java programming language.

## Code Breakdown

Let's first review the entire code:

```java
public class PasswordStrengthIndicator extends View {

    private int passwordStrength = 0; // range 0 - 10
    private final Paint filledPaint;
    private final Paint unfilledPaint;

    public PasswordStrengthIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);

        filledPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        unfilledPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        unfilledPaint.setColor(ContextCompat.getColor(context, R.color.grey)); // Color of unfilled dots
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int width = getWidth();
        int height = getHeight();
        int dotWidth = width / 20; // Adjusted to allow space for gaps
        int dotHeight = dotWidth / 2;
        float radius = 5 * getResources().getDisplayMetrics().density; // 5dp to px
        int totalDotWidth = 10 * dotWidth + 9 * dotWidth; // total width of all dots and spaces
        int start = (width - totalDotWidth) / 2; // the starting x value to center the dots

        for (int i = 0; i < 10; i++) {
            int x = start + i * (dotWidth * 2); 
            RectF rectF = new RectF(x, (height - dotHeight) / 2, x + dotWidth, (height + dotHeight) / 2);

            if (i < passwordStrength) {
                if (passwordStrength <= 3) {
                    filledPaint.setColor(ContextCompat.getColor(getContext(), R.color.red));
                } else if (passwordStrength <= 7) {
                    filledPaint.setColor(ContextCompat.getColor(getContext(), R.color.yellow));
                } else {
                    filledPaint.setColor(ContextCompat.getColor(getContext(), R.color.green));
                }
                canvas.drawRoundRect(rectF, radius, radius, filledPaint);
            } else {
                canvas.drawRoundRect(rectF, radius, radius, unfilledPaint);
            }
        }
    }

    public void setPasswordStrength(int passwordStrength) {
        this.passwordStrength = passwordStrength;
        invalidate();
    }
}
```
The class `PasswordStrengthIndicator` extends `View`, the base class for widgets in Android, which allows it to be used in your UI layouts.

### Initializing Paint Objects

In the constructor, we initialize two `Paint` objects. The `Paint` class holds style and color information about how to draw geometries, text, and bitmaps. In our case, we use two separate instances: `filledPaint` for filled dots and `unfilledPaint` for unfilled ones.

### Drawing on Canvas

The drawing takes place in the `onDraw(Canvas canvas)` method. We first determine the width and height of our widget and the size of the dots that represent the password strength.

We calculate the total width required for the dots and the gaps between them and calculate a starting point to center them. We then loop through 10 times (our password strength range is 0 - 10), drawing either a filled or unfilled dot depending on the current password strength.

The color of the filled dots changes based on the password strength:
- Strength less than or equal to 3: Red
- Strength between 4 and 7: Yellow
- Strength greater than 7: Green

### Updating the Password Strength

Finally, we have a public method `setPasswordStrength(int passwordStrength)`. This method sets the password strength and calls `invalidate()`. The `invalidate()` method tells the system that this view should be redrawn, causing the `onDraw` method to be called again.

## How Does This Work?

This password strength indicator is purely a visual representation. You must create a mechanism to calculate the actual strength of the password entered by the user. The calculation can be based on the inclusion of uppercase letters, lowercase letters, digits, special characters, and the overall length of the password.

Whenever the password input changes, call `setPasswordStrength(int passwordStrength)` on this view with the new strength. The indicator will update automatically, providing real-time feedback to the user.

## Further Customizations

The customization possibilities are endless. You could modify the colors to better fit your app's theme. Moreover, you could adjust the dot size and radius to best suit your needs. You might also consider creating a gradient password strength meter for a more visually pleasing indicator.

## Color Resources

In the provided code, we refer to color resources like `R.color.red`, `R.color.yellow`, and `R.color.green`. These color resources should be defined in your project's `res/values/colors.xml` file. You can learn more about color resources in the Android Developer's guide to [More Resource Types](https://developer.android.com/guide/topics/resources/more-resources#Color).

## How to Use It in Your Layout

To utilize the `PasswordStrengthIndicator` in your Android layout, use the XML code snippet below:

```xml
<com.yourPackage.PasswordStrengthIndicator
    android:id="@+id/password_strength_indicator"
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:layout_gravity="center"/>
```
Replace `com.yourPackage` with the actual package name where you have placed the `PasswordStrengthIndicator` class.

And in java, call using this way to set strength according to your needs:

```java
PasswordStrengthIndicator passwordStrengthIndicator = findViewById(R.id.password_strength_indicator);
passwordStrengthIndicator.setPasswordStrength(10);
```

## Lastly
I hope this post has given you a thorough understanding of how to create a visually appealing and interactive password strength indicator. With this simple guide, you can create your very own password strength meter and customize it according to your app's requirements.

## More

- [Navigating Pages with Ease: Tap Left/Right — A Custom ViewPager in Android](https://blog.rejowan.com/tutorial/code/java/navigating-pages-with-ease-tap-left-right-a-custom-viewpager-in-android/)
- [RecyclerView Last Item Extra Bottom Margin](https://blog.rejowan.com/tutorial/code/java/recyclerview-last-item-extra-bottom-margin/)
- [Making Android Views Draggable: A Practical Guide](https://blog.rejowan.com/tutorial/code/java/making-android-views-draggable-a-practical-guide/)
- [Hide the Soft Keyboard and Remove Focus from EditText in Android](https://blog.rejowan.com/tutorial/code/java/hide-the-soft-keyboard-and-remove-focus-from-edittext-in-android/)
- [Android SearchView OnCloseListener Not Working? Here’s How to Fix It](https://blog.rejowan.com/tutorial/code/java/android-searchview-oncloselistener-not-working-here-is-how-to-fix-it/)
- [CardView vs. MaterialCardView](https://blog.rejowan.com/tutorial/design/cardview-vs-materialcardview/)
- [Android 13’s Restricted Setting: A Stronghold Against Malicious Apps](https://blog.rejowan.com/news/android-news/android-13s-restricted-setting-a-stronghold-against-malicious-apps/)
- [Boost Your Android Development with ADB Idea Plugin](https://blog.rejowan.com/tutorial/android-studio/boost-your-android-development-with-adb-idea-plugin/)
-  [Troubleshooting “Execution Failed for Task app:mergeDebugResources” Error in Android XML Files](https://blog.rejowan.com/qa/android-qa/troubleshooting-execution-failed-for-task-appmergedebugresources-error-in-android-xml-files/)
- [Android Activity Lifecycle: A Comprehensive Guide](https://blog.rejowan.com/tutorial/series/android-basics/android-activity-lifecycle-a-comprehensive-guide/)