Tuesday, 1 January 2013

How to create custom Text Fields in Android

Advertisement


From Developer.android.com: “A text field allows the user to type text into your app. It can be either single line or multi-line. Touching a text field places the cursor and automatically displays the keyboard. In addition to typing, text fields allow for a variety of other activities, such as text selection (cut, copy, paste) and data look-up via auto-completion.”

In this tutorial, we show you how to customize some Text Fields. We want to introduce some Text Fields with specifying the Keyboard Type and specifying Keyboard Actions.

Here is a result of this tutorial:

Android Custom TextField - Figure 4


This project is developed in Eclipse 4.2.0.
1. Make some Text Fields by XML Layout: The main layout includes some TextViews, some EditTexts, one Custom AutoCompleteTextView and one button.



<?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="wrap_content" 
    android:orientation="vertical">
      
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="User Name"/>
    <EditText
        android:id="@+id/editText_username"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:background="@drawable/edittext" >
    </EditText>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Password"/>
    <EditText
        android:id="@+id/editText_password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:ems="10"
        android:inputType="textPassword"
        android:background="@drawable/edittext" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Email Address"/>
    <EditText
        android:id="@+id/editText_emailaddress"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:ems="10"
        android:inputType="textEmailAddress"
        android:background="@drawable/edittext" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Phone Number"/>
    <EditText
        android:id="@+id/editText_phonenumber"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:ems="10"
        android:inputType="phone"
        android:background="@drawable/edittext"
        android:imeOptions="actionDone"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Web Address"/>
    <EditText
        android:id="@+id/editText_webaddress"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:ems="10"
        android:background="@drawable/edittext"
        android:imeOptions="actionGo"/>
   
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Nationality"/>
    <com.example.textfieldcontrol.CustomAutoCompleteTextView
        android:id="@+id/autoCompleteTextView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:ems="10"     
        android:completionThreshold="1"
        android:ellipsize="end"
        android:maxLines="1"
        android:background="@drawable/edittext"/>
 
    <Button android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Get all edit text"
        android:onClick="button_click"
        android:layout_marginTop="15dp"/>
   
</LinearLayout>

For android:background attribute of all EditTexts and AutoCompleleTextView we need a edittext.xml file in folder drawable

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
           <shape android:shape="rectangle">
               <gradient android:startColor="#40FFE600"
                   android:centerColor="#60FFE600"android:endColor="#90FFE600"
                   android:angle="270"android:centerX="0.5" android:centerY="0.5"/>
               <stroke android:width="5dp"android:color="#50FF00DE" />
               <corners android:radius="7dp"/>
               <padding android:left="10dp"android:top="6dp" android:right="10dp"
                   android:bottom="6dp"/>
           </shape>
       </item>
       <item android:state_focused="true">
           <shape>
               <gradient android:startColor="#40CB1759"
                   android:centerColor="#60CB1759"android:endColor="#90CB1759"
                   android:angle="270"android:centerX="0.5" android:centerY="0.5"/>
               <stroke android:width="5dp"android:color="#50ff0000" />
               <corners android:radius="7dp"/>
               <padding android:left="10dp"android:top="6dp" android:right="10dp"
                   android:bottom="6dp"/>
           </shape>
       </item>
       <item>
           <shape>
               <gradient android:startColor="#402168D2"
                   android:centerColor="#602168D2"android:endColor="#9966FF"
                   android:angle="270"android:centerX="0.5" android:centerY="0.5"/>
               <stroke android:width="5dp"android:color="#50ff0000" />
               <corners android:radius="7dp"/>
               <padding android:left="10dp"android:top="6dp" android:right="10dp"
                   android:bottom="6dp"/>
           </shape>
       </item>
</selector>

For custom AutoCompleteTextView we need create a class namely CustomAutoCompleteTextView to Source Folder

package com.example.textfieldcontrol;

import java.util.HashMap;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.AutoCompleteTextView;

/** Customizing AutoCompleteTextView to return Country Name  
 *  corresponding to the selected item
 */
public class CustomAutoCompleteTextView extends AutoCompleteTextView {
      
       public CustomAutoCompleteTextView(Context context, AttributeSet attrs) {
              super(context, attrs);
       }

       /** Returns the country name corresponding to the selected item */
       @Override
       protected CharSequence convertSelectionToString(Object selectedItem) {
              /** Each item in the autocompetetextview suggestion list is a hashmap object */
              HashMap<String, String> hm = (HashMap<String, String>) selectedItem;
              return hm.get("txt");
       }
}
And create layout file for CustomAutoCompleteTextView. Locate file in res/layout folder
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"   
     >
    
    <ImageView
               android:id="@+id/flag"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:contentDescription="@string/hello_world"
               android:padding="10dp"
       />
       
       <TextView
               android:id="@+id/txt"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:textSize="15dp"  
               android:padding="10dp"
               android:textColor="#330099"
              
       /> 
</LinearLayout>
2. Code for main activity: Add click listener for the ImageButton
The code below performs a number of tasks, including:
-          For the Web address Edit Text, when User click on the Go Button on Soft Keyboard, the Keyboard should be hidden and the Website link that User have typed before will open with the default Browser on device.
-          Setting adapter for Custom AutoCompleteTextView
-          Get text on all EditTexts when click on the button
public class TextfieldActivity extends Activity {
    CustomAutoCompleteTextView autoComplete;
       EditText edit_username;
       EditText edit_password;
       EditText edit_emailaddress;
       EditText edit_phonenumber;
       EditText edit_webaddress;
       EditText edit_nationality;
       // Array of strings storing country names
    String[] countries = new String[] {
              "Argentina",
            "India",
            "Pakistan",
            "Sri Lanka",
            "China",
            "Bangladesh",
            "Nepal",
            "Afghanistan",
            "North Korea",
            "South Korea",
            "Japan",
            "Vietnam",
            "Venezuela"
    };
   
 // Array of integers points to images stored in /res/drawable-ldpi/
    int[] flags = new int[]{
                     R.drawable.argentina,
                     R.drawable.india,
                R.drawable.pakistan,
                R.drawable.srilanka,
                R.drawable.china,
                R.drawable.bangladesh,
                R.drawable.nepal,
                R.drawable.afghanistan,
                R.drawable.nkorea,
                R.drawable.skorea,
                R.drawable.japan,
                R.drawable.vietnam,
                R.drawable.venezuela
    };
       @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_textfield);
        edit_username = (EditText)findViewById(R.id.editText_username);
       edit_password = (EditText)findViewById(R.id.editText_password);
       edit_emailaddress = (EditText)findViewById(R.id.editText_emailaddress);
       edit_phonenumber = (EditText)findViewById(R.id.editText_phonenumber);
        edit_webaddress = (EditText)findViewById(R.id.editText_webaddress);
       
        edit_webaddress.setOnEditorActionListener( new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_GO ||
                        event.getAction() == KeyEvent.ACTION_DOWN &&
                        event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                     // open website
                                    String url = edit_webaddress.getText().toString();
                     Intent i = new Intent(Intent.ACTION_VIEW);
                     i.setData(Uri.parse(url));
                     startActivity(i);
                     // hide keyboard
                     InputMethodManager input = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                     input.hideSoftInputFromWindow(edit_webaddress.getWindowToken(), 0);
                    return true;
                }
                return false;
            }
        });
        //////////////////////////////
     // Each row in the list stores country name, currency and flag
        List<HashMap<String,String>> aList = newArrayList<HashMap<String,String>>();
        for(int i=0;i<13;i++){
                HashMap<String, String> hm = newHashMap<String,String>();
            hm.put("txt", countries[i]);
            hm.put("flag", Integer.toString(flags[i]) );
            aList.add(hm);
        }
        // Keys used in Hashmap
        String[] from = { "flag","txt"};
        // Ids of views in listview_layout
        int[] to = { R.id.flag,R.id.txt};
        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.autocomplete_layout, from, to);
       
        // Getting a reference to CustomAutoCompleteTextView of activity_main.xml layout file
        autoComplete = ( CustomAutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
        /** Defining an itemclick event listener for the autocompletetextview */
        OnItemClickListener itemClickListener = new OnItemClickListener() {
              @Override
              public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
                     /** Each item in the adapter is a HashMap object.
                      *  So this statement creates the currently clicked hashmap object
                      * */
                     HashMap<String, String> hm = (HashMap<String, String>) arg0.getAdapter().getItem(position);
              InputMethodManager input = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
              input.hideSoftInputFromWindow(autoComplete.getWindowToken(), 0);
              }
              };
              /** Setting the itemclick event listener */
        autoComplete.setOnItemClickListener(itemClickListener);
        /** Setting the adapter to the listView */
        autoComplete.setAdapter(adapter);    
    }

    @SuppressWarnings("deprecation")
       public void button_click(View view){
       // show alert
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("All edit text content");
        alertDialog.setMessage("User Name: " + edit_username.getText().toString() + "\nPassword: "
                     + edit_password.getText().toString() + "\nEmail address: "
                     + edit_emailaddress.getText().toString() + "\nPhone number: "
                     + edit_phonenumber.getText().toString() + "\nWeb address: "
                     + edit_webaddress.getText().toString() + "\nNationality: "
                     + autoComplete.getText().toString());
        alertDialog.setButton("Close", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int which) {
       // here you can add functions
               }
        });                      
        alertDialog.show();
    }
}
3. DEMO
3.1. Run Apllication

Android Custom TextField - Figure 1


3.2. Some Soft Keyboard with specifying Keyboard Type for each Edit Text
 With attibute: 
 android:inputType="phone"  
        android:imeOptions="actionDone"


Android Custom TextField - Figure 2

              android:inputType="textEmailAddress"
        android:imeOptions="actionNext"

Android Custom TextField - Figure 3

3.3. Work with custom AutoCompleteTextView

Android Custom TextField - Figure 4


3.4. When click on the button

Android Custom TextField - Figure 5


You can download all source codes from here.
Refer: http://wptrafficanalyzer.in/blog/customizing-autocompletetextview-to-display-images-and-text-in-the-suggestion-list-using-simpleadapter-in-android/


EmoticonEmoticon