Tuesday, 28 May 2013

Android Password Field

In Android, you can use “android.widget.EditText“, with inputType="textPassword" for password component.
In this tutorial, we show you how to use XML to create a password field. When you click on the button, the password value will be displayed as a message (toast message).

2. Password

Openres/layout/activity_main.xmlfile, add a password component.
<LinearLayout 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"
tools:context=".MainActivity"
android:orientation="vertical" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/editPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword" >

<requestFocus />
</EditText>
<Button
android:id="@+id/btnDisplayPass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display Password" />

</LinearLayout>

3. Code

Inside activity "onCreate" method, attach a click listener on button, to display the password value.

package com.learnsimply.edittextpassword;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
EditText edPass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edPass = (EditText)findViewById(R.id.editPassword);
Button btnDisplay = (Button)findViewById(R.id.btnDisplayPass);
btnDisplay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, edPass.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}


Run the application





Download Source Code Android Password Example.zip

No comments:

Post a Comment