Tuesday, January 1, 2013

16 How to create custom Text Fields in Android


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 = new ArrayList<HashMap<String,String>>();
        for(int i=0;i<13;i++){
                HashMap<String, String> hm = new HashMap<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/

16 comments:

  1. After checking out a few of the blog articles on your blog, I honestly like your way of writing a blog.
    I book marked it to my bookmark website list and will be
    checking back soon. Take a look at my web site as well and tell me your opinion.


    Look into my weblog ... restaurants

    ReplyDelete
  2. Great site. Plenty of helpful info here. I'm sending it
    to some buddies ans additionally sharing in delicious.
    And obviously, thanks in your sweat!

    my web page; landmark

    ReplyDelete
  3. always i used to read smaller articles or reviews which also clear their motive, and that is also happening with this article which I am reading
    at this time.

    my blog post dental services

    ReplyDelete
  4. great points altogether, you just won a brand new reader.
    What could you recommend about your put up that you simply made a few days ago?
    Any positive?|

    Take a look at my blog program pit 2013 ()

    ReplyDelete
  5. I am extremely impressed with your writing skills and also with
    the layout on your blog. Is this a paid theme or did
    you customize it yourself? Anyway keep up the excellent quality writing,
    it's rare to see a nice blog like this one nowadays.

    my page web design

    ReplyDelete
  6. Have you ever thought about including a little bit more
    than just your articles? I mean, what you say is fundamental
    and everything. But imagine if you added some great graphics or videos
    to give your posts more, "pop"! Your content is excellent but with pics and clips, this site could undeniably be one of the very best in its niche.
    Terrific blog!|

    Look into my page - darmowy program pit 2013 ()

    ReplyDelete
  7. I almost never drop responses, however I looked at some oof
    the remarks here "How to create custom Text Fields in Android".
    I actuwlly do have some questins for you iff it's okay. Could
    itt be only me or do a few of the remarks appear as iff they are written by brain dead visitors?
    :-P And, iif you are posting on additional social sites,
    I would like to follow you. Could you list of all oof all
    your public pages like your twitter feed, Facebook page or linkedin profile?


    Here is my page ... plateforme projets solidaires

    ReplyDelete
  8. Hey tҺere would yοu mind lettiոǥ me know which wеb host you're utilizing?
    I've loaded your blog in 3 different browsers and I must
    say this blog loads a lot ԛuicker theո most. Can you recommend a goοd
    web hostinց ρrovіder at a fair price? Cheers, I appreciate it!


    Feel free to visit my site; reсrutement, http://www.serefconsultants.com/,

    ReplyDelete
  9. Hi, I do believe this is a great blog. I stumbledupon it ;) I'm
    going to return yet again since I saved as a favorite it.
    Money and freedom is the bst way to change, may you bbe
    rich and continue to guide others.

    Check out mmy weblog spécialiste référencement ()

    ReplyDelete
  10. always i used to read smaller content that als clear
    their motive, and that iis aleo happening with this paragraph whihh
    I am reading at this place.

    Look into my blog post; investissement participatif

    ReplyDelete
  11. These are actually great ideas in concerning blogging. You have
    touched some pleasant points here. Any way keep up wrinting.


    My web site: lafayette

    ReplyDelete
  12. Hello to all, the contents existing at this site are actually
    awesome for people experience, well, keep up the
    nice work fellows.

    Feel free to surf to my website; Towing Software

    ReplyDelete
  13. Truly no atter if someone doesn't know thwn its up tto other people
    thatt they will assist, so here it takes place.


    My web site: Synthese audit Informatique

    ReplyDelete
  14. I simply want to say I’m very new to blogs and actually loved you’re blog site. Almost certainly I’m going to bookmark your blog post . You absolutely come with great well written articles. Thanks a lot for sharing your blog.

    Android training in chennai with placement | Android Training in chennai |Android Training in Velachery

    ReplyDelete
  15. Text fields allow the user to input text, select text (cut, copy, paste), and lookup data via auto-completion.Android Training in chennai | Android Training|Android Training in chennai with placement | Android Training in velachery

    ReplyDelete
  16. Thanks for your information and valuable time,it is really guides us.
    Android Training in chennai

    ReplyDelete