Krishna Krishna - 2 months ago 15
Android Question

Make EditText editable programmatically

I have a layout with one textView and one EditText and a button. EditText is made as non editable in xml file. I want to make it enabled via code.

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:id="@+id/textView12"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
/>

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/etName"
android:layout_below="@+id/textView12"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:editable="false"
/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/edit"
android:onClick="edit"
android:id="@+id/btnName"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />

Answer Source

Remove android:editable="false" this line from android xml file as this method is deprecated in android. and use below code to do so.

  • Make EditText non editable using java code

In onCreate of activity do the following after setContentView() method

EditText text = (EditText) findViewById(R.id.etName);
text.setTag(text.getKeyListener());
text.setKeyListener(null);
  • And make it editable using following code

    text.setKeyListener((KeyListener) textView.getTag());
    

Hope it'll help.