以编程方式设置TextInputLayout的样式

6

有没有一种方法可以通过编程方式自定义这些 TextInputLayout 属性:

  • textColorHint
  • colorAccent
  • colorControlNormal
  • colorControlActivated
  • textSelectHandle

我知道如何使用主题属性来设置它们的样式,但我正在工作的项目动态加载颜色信息,据我所知,在运行时更改主题/样式值的方法是不存在的。


你可以在这里找到答案:https://dev59.com/klwZ5IYBdhLWcg3wM9_Z#31723120 - guisantogui
1
问题是要通过编程来设置它。 - Ryno C.
1个回答

4
我编写了textInputLayout实现,可以设置任何颜色的下划线和错误提示,并在顶部显示错误信息。请参考以下图片: enter image description here enter image description here enter image description here
public class TextInputLayoutUseful extends TextInputLayout {
private CharSequence originalHint = "";

public TextInputLayoutUseful(Context context) {
    super(context);
    init();
}

public TextInputLayoutUseful(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public TextInputLayoutUseful(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private void init() {
    this.originalHint = getHint();
    setErrorEnabled(false);
}

/**
 * - put error text into top floating label
 * - colorized layout
 *
 * @param error error text
 */
@Override
public void setError(@Nullable CharSequence error) {
    if (error == null) {
        setHint(originalHint);
        setHintTextAppearance(R.style.InputLayoutNormalHint);
        setUnderlineColor(R.color.input_normal_accent);
    } else {
        setHint(error);
        setHintTextAppearance(R.style.InputLayoutErrorHint);
        setUnderlineColor(R.color.input_error_accent);
    }
}

/**
 * colorized layout specified green color
 *
 * @param acceptedHint text for floating label
 */
public void setGreenError(@NonNull CharSequence acceptedHint) {
    setHint(acceptedHint);
    setHintTextAppearance(R.style.InputLayoutAcceptedHint);
    setUnderlineColor(R.color.input_accepted_accent);
}

private void setUnderlineColor(@ColorRes int colorRes) {
    if (getEditText() != null) {
        getEditText().getBackground().mutate().setColorFilter(ContextCompat.getColor(getContext(), colorRes), PorterDuff.Mode.SRC_ATOP);
    }
}
}

样式

<style name="InputLayoutErrorHint" parent="TextAppearance.AppCompat">
    <item name="android:textColor">@color/input_error_accent</item>
</style>

<style name="InputLayoutNormalHint" parent="TextAppearance.AppCompat">
    <item name="android:textColor">@color/input_normal_accent</item>
</style>

<style name="InputLayoutAcceptedHint" parent="TextAppearance.AppCompat">
    <item name="android:textColor">@color/input_accepted_accent</item>
</style>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接