繁体   English   中英

无法为自定义编辑文本应用样式

[英]Cannot apply style for custom edit text

我正在尝试以编程方式应用 TextInputLayout 主题来创建一次自定义编辑文本并在任何地方使用它。

这是我的自定义编辑文本类:

package com.enjoyapps.weddingapp.view;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import androidx.appcompat.view.ContextThemeWrapper;

import com.enjoyapps.weddingapp.R;
import com.google.android.material.textfield.TextInputLayout;

public class CustomEditText extends TextInputLayout {


    public CustomEditText(Context context) {
        super(new ContextThemeWrapper(context, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox));
        init();
    }

    public CustomEditText(Context context, AttributeSet attrs) {
//        super(context, attrs);
        super(new ContextThemeWrapper(context, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox), attrs);
        init();
    }

    public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(new ContextThemeWrapper(context, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox), attrs, defStyleAttr);
        init();
    }

    private void init() {
        setBoxStrokeColor(Color.BLUE);
        setBoxCornerRadii(50,50,50,50);
        setBoxBackgroundColor(Color.BLUE);

    }
}

如您所见,在构造函数中,我将样式设置为:

new ContextThemeWrapper(context, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox)

当我将自定义编辑文本添加到 xml 时,它没有获得我在 init 方法中设置的属性。

但是当我在 xml 中应用相同的主题时,它正在工作并从 init 方法获取 all 属性。

<com.enjoyapps.weddingapp.view.CustomEditText
    android:layout_width="300dp"
    android:layout_centerInParent="true"
    android:layout_height="50dp">

    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</com.enjoyapps.weddingapp.view.CustomEditText>

使用您的应用程序的哪种风格? 只需添加到您的主要风格:

<item name="editTextStyle">@style/YourStyle</item>

例子:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
   <!-- Customize your theme here. -->
   <item name="colorPrimary">@color/colorPrimary</item>
   <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
   <item name="colorAccent">@color/colorAccent</item>

   <item name="editTextStyle">@style/YourStyle</item>
</style>

花了一些挖掘才发现问题。 显然, TextInputLayout使用boxBackgroundMode以使用来自不同样式的某些属性。

除了ContextThemeWrapper ,您还必须为TextInputLayout设置boxBackgroundMode

因此,如果您正在使用:

  • FilledBox :你需要使用BOX_BACKGROUND_FILLED
  • OutlinedBox :您需要使用BOX_BACKGROUND_OUTLINE

在您的情况下,只需将setBoxBackgroundMode(BOX_BACKGROUND_OUTLINE)添加到您的init()

private void init() {
    // ... some styling here

    setBoxBackgroundMode(BOX_BACKGROUND_OUTLINE);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM