noe256471
noe256471

Reputation: 75

How to set padding fixed in EditText programmatically?

enter image description here

When I change textSize attribute lower than 18sp the height changes. And when I add a drawable programmatically it also changes. What I want to do is keep the height fixed. How to do this?

See below, the problem is EditText 2. I want to keep the height fixed when I add the drawable in Java.

// layout.xml
<EditText
    android:id="@+id/edittext"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#C8E6C9"
    android:paddingVertical="12dp" />
<EditText
    android:id="@+id/edittext2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:background="#C8E6C9"
    android:paddingVertical="12dp"
    android:textSize="14sp" />

// EditText 1
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    if (count > 0) {
        editText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_close, 0);
    } else {
        editText.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
    }
}

// EditText 2
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    if (count > 0) {
        editText1.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_close, 0);
    } else {
        editText1.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
    }
}

Upvotes: 0

Views: 192

Answers (1)

Henry Twist
Henry Twist

Reputation: 5980

I wouldn't expect there to be a solution to this without changing your implementation slightly. The EditText wouldn't ever be able to measure it's height properly without having some information about the drawable in advance.

So a few solutions for you:

Minimum height

If you know the height of the drawable in advance, you could set a minimum height of the EditText to match it.

Just use a separate ImageView

Wrap the EditText in a horizontal LinearLayout with an ImageView containing your drawable.


You could also play around with changing the tint or alpha of the drawable instead of adding/removing it but I would recommend against it.

As a side note it seems like your intended use case is a button to clear the EditText? If so I would definitely go for the second approach but using an ImageButton so as to use the standard Android click handling instead of having to fiddle with touch listeners (which I think would be the only way to detect touch on a compound drawable).

Finally if you're using the Material Components library, the TextInputLayout component has the functionality for clearing a text field baked in, which you can read about here: Text fields.

Upvotes: 2

Related Questions