簡體   English   中英

如何以編程方式在 EditText 中設置填充?

[英]How to set padding fixed in EditText programmatically?

在此處輸入圖像描述

當我將 textSize 屬性更改為低於 18sp 時,高度會發生變化。 當我以編程方式添加可繪制對象時,它也會發生變化。 我想要做的是保持高度固定。 這個怎么做?

見下文,問題是 EditText 2。當我在 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);
    }
}

如果不稍微改變你的實現,我不希望有一個解決方案。 如果事先沒有關於可繪制對象的一些信息, EditText將永遠無法正確測量它的高度。

因此,為您提供了一些解決方案:

最小高度

如果您事先知道可繪制對象的高度,則可以設置EditText的最小高度以匹配它。

只需使用單獨的ImageView

使用包含您的可繪制對象的ImageViewEditText包裝在水平LinearLayout中。


您也可以嘗試更改可繪制對象的色調或 alpha,而不是添加/刪除它,但我建議不要這樣做。

作為旁注,您的預期用例似乎是清除EditText的按鈕? 如果是這樣,我肯定會為第二種方法使用 go,但使用ImageButton以便使用標准的 Android 點擊處理,而不必擺弄觸摸偵聽器(我認為這是檢測復合可繪制對象上的觸摸的唯一方法)。

最后,如果您使用 Material Components 庫, TextInputLayout組件具有清除內置文本字段的功能,您可以在此處閱讀:文本字段

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM