Search code examples
androidandroid-edittext

EditText - have default text that cannot be deleted, and cover text with background after leaving EditText


I am creating an email form and would like to have text in an EditText that cannot be deleted. On the screenshot below, the To could not be deleted.

Cannot delete From - is this possible?

If anyone has suggestions on how to achieve the above, it would be great - Thanks.

My current code for the To EditText box:

<EditText
    android:id="@+id/editText2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginTop="0dp"
    android:hint="@string/email_to" >
</EditText>

The problem is android:hint text dissappears when the user starts to text, and android:text can be deleted by the user.

How do we have text that cannot be deleted? Thanks.

Note:

Also, I would like to note that I have a method that clears text using a clear button - this works fine - but I am hoping that it would not delete the fixed text (If I got that implemented!).. Here`s the code for that:

private void clearForm(ViewGroup group)
{       
    for (int i = 0, count = group.getChildCount(); i < count; ++i) {
    View view = group.getChildAt(i);
    if (view instanceof EditText) {
        ((EditText)view).setText("");
    }

    if(view instanceof ViewGroup && (((ViewGroup)view).getChildCount() > 0))
        clearForm((ViewGroup)view);
}
}

SOLUTION:

Managed a roundabout way of doing this.. I created a TextView and EditText within a nested Linear Layout. I turned off the border in the EditText using android:background="#00000000".

I created an xml file in the drawable folder, and refered to this in the relevant linear layout like this: android:background="@drawable/customxml"


Solution

  • To get the visual appearance you want, include a horizontal LinearLayout containing a text view and an EditView. Turn off the border around the EditView (there's an attribute that does that (I think it's android:shadowColor) ) Play around with margins and padding to get them to be adjacent to each other. Set the background color on the linear layout to put a border around the combined pair.

    I wouldn't worry much about efficiency. You aren't nesting very deeply. The biggest challenge is going to be getting it to look like a single view.

    Edit: Another thought. If that doesn't work, you could make the "To" a drawable, and set it using the android:drawableLeft attribute.