Monday, July 28, 2014

Password field in Android

Wish to have a Password field in your Android app? You can use “android.widget.EditText“, with inputType="textPassword" to accomplish the task. In this tutorial, we shall learn how to use XML to create a password field, a label field and a normal button. When the button is clicked, the password value will be displayed as a toast message on the screen.

1. Strings.xml file

Open the "strings.xml” file, and add some custom strings.

File : res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MyApp</string>
<string name="lblPassword">Enter Your Password :</string>
<string name="btn_submit">Submit</string>  
</resources>

2. Add the Password field

Open the layout file "main.xml" and add a password component using the EditText field and marking the inputType as "textPassword".

File : res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
<TextView android:id="@+id/lblPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/lblPassword"
        android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText android:id="@+id/txtPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#EECCFF"
        android:inputType="textPassword" >
<requestFocus />
</EditText>
<Button android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn_submit" />
</LinearLayout>

3. Java Code

Inside the activity “onCreate()” method, attach a click listener on button, to display the password value when it is pressed.

File : Main.java

package com.endeavour.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Main extends Activity {

private EditText password;
private Button btnSubmit;

@Override
  public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       addListenerOnButton();
}

public void addListenerOnButton() {
       password = (EditText) findViewById(R.id.txtPassword); 
       btnSubmit = (Button) findViewById(R.id.btnSubmit);
       btnSubmit.setOnClickListener(new OnClickListener() {
       @Override
       public void onClick(View v) {
      Toast.makeText(HomeScreen.this, password.getText(),Toast.LENGTH_SHORT).show();
      }
    });
}
}

4. Output

i. Password field being displayed.


ii. When Password is entered and Submit button is pressed.
 

No comments:

Post a Comment