Tuesday, August 18, 2015

How to disable EditText in Android

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#cfd4d3"
    >
    <!--
        android:editable="false"
        This attribute is deprecated

        android:inputType
            The type of data being placed in a text field,
            used to help an input method decide how to let the user enter text.

        android:inputType="none"
            There is no content type. The text is not editable.

        android:focusableInTouchMode="false"
        android:focusable="false"
            You can also use this two attributes to disable EditText

        android:enabled="false"
            This attribute also disable the EditText

        Find your best technique.
    -->
    <EditText
        android:id="@+id/et"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:hint="Input your country"
        android:padding="10dp"
        android:inputType="none"
        android:editable="false"
        />
    <EditText
        android:id="@+id/et_city"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:hint="Input your City"
        android:padding="10dp"
        android:layout_below="@+id/et"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.text.InputType;
import android.widget.EditText;


public class MainActivity extends Activity {

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

        // Get the widgets reference from XML layout
        final EditText et = (EditText) findViewById(R.id.et);
        final EditText et_city = (EditText) findViewById(R.id.et_city);

        /*
            setInputType(int type)
                Set the type of the content with
                a constant as defined for inputType.
         */
        // Set the EditText input type null
        et_city.setInputType(InputType.TYPE_NULL);
        /*
            public void setKeyListener (KeyListener input)
                Sets the key listener to be used with this
                TextView. This can be null to disallow user input.
         */
        et_city.setKeyListener(null);
 }
}
More android examples