Android EditText onFocus and onBlur Example

Most web developers are familiar with the onFocus and onBlur events on a web page so that they can take certain actions based on them. In android an EditText can set the OnFocusChangeListener and then implement the onFocusChange method to listen for changes to that view. In this example we use the OnFocusChangeListener to set some text inside the input boxes and when an EditText inside a ListView row get in focus we highlight the complete row by changing the background color.

Android EditText onFocus and onBlur Example
Android EditText onFocus inside ListView

Android Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.as400samplecode"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Application main Layout - activity_main.xml

<?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:padding="5dp">

 <TextView android:id="@+id/textView1" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_alignParentTop="true" android:text="Some EditText views ..."
  android:textAppearance="?android:attr/textAppearanceMedium"
  android:textStyle="bold" />

 <EditText android:id="@+id/editText1" android:layout_width="fill_parent"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_alignParentTop="false" android:layout_below="@id/textView1"
  android:ems="10" />

 <EditText android:id="@+id/editText2" android:layout_width="fill_parent"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_below="@+id/editText1" android:ems="10" />

 <TextView android:id="@+id/textView2" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_below="@+id/editText2" android:text="EditText views inside a ListView"
  android:textAppearance="?android:attr/textAppearanceMedium"
  android:textStyle="bold" />

 <ListView android:id="@+id/listView1" android:layout_width="match_parent"
  android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView2"
  android:layout_below="@+id/textView2" />

</RelativeLayout>

ListView Row Layout - my_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent" android:layout_height="wrap_content"
 android:orientation="vertical" android:padding="6dip">

 <EditText android:id="@+id/myInputText" android:layout_width="100sp"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_alignParentTop="true" android:ems="10" />

 <TextView android:id="@+id/country" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_alignBottom="@+id/myInputText"
  android:layout_alignParentRight="true" android:text="Medium Text"
  android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Application main Activity - MainActivity.java

package com.as400samplecode;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

 private EditText myEditText1, myEditText2;
 MyCustomAdapter dataAdapter = null;

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

  //get reference to the EditText
  myEditText1 = (EditText) findViewById(R.id.editText1);
  //set the onFocusChange listener
  myEditText1.setOnFocusChangeListener(myEditTextFocus);

  //get reference to the EditText
  myEditText2 = (EditText) findViewById(R.id.editText2);
  //set the onFocusChange listener
  myEditText2.setOnFocusChangeListener(myEditTextFocus);

  //Generate list View from ArrayList
  displayListView();

 }

 private void displayListView() {

  //Array list of countries
  ArrayList<String> countryList = new ArrayList<String>();
  countryList.add("Aruba");
  countryList.add("Anguilla");
  countryList.add("Netherlands Antilles");
  countryList.add("Antigua and Barbuda");
  countryList.add("Bahamas");
  countryList.add("Belize");
  countryList.add("Bermuda");
  countryList.add("Barbados");
  countryList.add("Canada");
  countryList.add("Costa Rica");
  countryList.add("Cuba");
  countryList.add("Cayman Islands");

  //create an ArrayAdaptar from the String Array
  dataAdapter = new MyCustomAdapter(this, R.layout.my_row, countryList);
  ListView listView = (ListView) findViewById(R.id.listView1);
  // Assign adapter to ListView
  listView.setAdapter(dataAdapter);

 }

 private class MyCustomAdapter extends ArrayAdapter<String> {

  private ArrayList<String> countryList;

  public MyCustomAdapter(Context context, int textViewResourceId, 
    ArrayList<String> countryList) {
   super(context, textViewResourceId, countryList);
   this.countryList = new ArrayList<String>();
   this.countryList.addAll(countryList);
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {

   if (convertView == null) {

    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = vi.inflate(R.layout.my_row, null);

   } 

   //get reference to the Editext inside the view that was inflated to create the row
   EditText myInputText = (EditText) convertView.findViewById(R.id.myInputText);
   //attach the onFocusChange listener to the EditText
   myInputText.setOnFocusChangeListener(new OnFocusChangeListener() {
    public void onFocusChange(View v, boolean gainFocus) {
     //onFocus
     if (gainFocus) {
      //set the row background to a different color
      ((View) v.getParent()).setBackgroundColor(Color.rgb(255, 248, 220));
     } 
     //onBlur
     else {
      //set the row background white
      ((View) v.getParent()).setBackgroundColor(Color.rgb(255, 255, 255));
     }
    }
   });

   TextView country = (TextView) convertView.findViewById(R.id.country);
   country.setText(countryList.get(position));
   return convertView;

  }

 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

 private OnFocusChangeListener myEditTextFocus =  new OnFocusChangeListener() {
  public void onFocusChange(View view, boolean gainFocus) {
   //onFocus
   if (gainFocus) {
    //set the text
    ((EditText) view).setText("In focus now");
   } 
   //onBlur
   else {
    //clear the text
    ((EditText) view).setText("");
   }
  };
 };

}

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.