How to change input type Number to Text of EditText in android

android, android-emulator, android-intent, android-layout

Solution

You could use a toggle button to switch between number to text and vice versa.

in your layout xml:

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="number" >

    <requestFocus />
</EditText>

<ToggleButton
    android:id="@+id/toggleButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="InputType"
    android:textOff="Text"
    android:textOn="Number" />

Activity class:

EditText ed;
ToggleButton edtb;

//flag : used in the added code

static boolean flag = false;

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

    ed = (EditText) findViewById(R.id.editText1);
    edtb = (ToggleButton) findViewById(R.id.toggleButton1);

    edtb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            if(isChecked)
            {
                ed.setInputType(InputType.TYPE_CLASS_TEXT);
            }
            else
            {
                ed.setInputType(InputType.TYPE_CLASS_NUMBER);
            }

        }
    });

  /* **Edited** Adding a way to achieve the same using EditText only. */

  ed.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if(flag)
            {
                ed.setInputType(InputType.TYPE_CLASS_TEXT);
                flag=false;
            }
            else
            {
                ed.setInputType(InputType.TYPE_CLASS_NUMBER);
                flag=true;
            }

        }
    });

}

Problem

I have a requirement in my project,that by default the input type of the Edittext is Number.How we can give an option to the User to change the input type Number to Text/Alphabets. Thanks Tiru

Original source