Here’s another quick tip to use when building your Android apps whether in Xamarin, or native in Java/Kotlin. Depending on the target audience of your application, you may find it necessary to add a password toggle button to your password EditText
to allow users to view and hide their password while typing it.
In this post, we will explore how to do this in Android natively while future posts will cover iOS (which is more involved) as well as building a Xamarin.Forms custom Entry
view (no renderer’s required!) to handle the toggling.
There are two places to achieve this in Android – in the xml of the layout resource, or in the code behind where manipulating the view. Luckily, Android (unlike iOS) has this feature built in to the properties of the TextInputLayout
control.
We get the ability to show the button as well as apply a custom Drawable
if we want!
Using the Layout Resource
Here is an example using the TextInputLayout
from the xml side to wrap an EditText:
activity_login.axml
<android.support.design.widget.TextInputLayout android:id="@+id/password_layout" android:layout_width="match_parent" android:layout_height="wrap_content" app:passwordToggleEnabled="true" app:passwordToggleTint="@android:color/white"> <android.support.design.widget.TextInputEditText android:id="@+id/password_editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:password="true" android:hint="Password" android:textColor="@android:color/white" android:inputType="textPassword" /> </android.support.design.widget.TextInputLayout>
Notice the two properties:
app:passwordToggleEnabled="true"
and
app:passwordToggleTint="@android:color/white"
These are the two that control showing the password toggle. Alternatively, you can set the
app:passwordToggleDrawable="@drawable/someDrawable"
Using Code
If you’re manipulating your TextInputLayout
in your code, you can also update these fields very easily:
LoginActivity.cs
public class LoginActivity : AppCompatActivity { protected override void OnCreate(Bundle savedInstance) { base.OnCreate(savedInstance); SetContentView(Resource.Layout.activity_login); var editTextLayout = FindViewById<TextInputLayout>(Resource.Id.password_layout); editTextLayout.PasswordVisibilityToggleEnabled = true; } }
That’s it!
Results
Take a look for yourself!
If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!
Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.