android - 使用 appcompat v7 自定义 EditText 样式

标签 android android-custom-view android-appcompat

我创建了一个扩展 EditText 的自定义 View ,并指定了一个属性样式来更改背景色。

public class CustomEditText extends EditText {

    public CustomEditText (Context context) {
        this(context, null);
    }

    public CustomEditText (Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.customEditTextStyle);
    }

    public CustomEditText (Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs,  R.attr.customEditTextStyle);
    }
    // Some other code...
}

然后我添加了一个属性样式:

<resources>
    <attr name="customEditTextStyle" format="reference" />
<resources>

我在我的应用程序中使用 Theme.AppCompat。我已经覆盖了 colorPrimary、colorPrimaryDark 和 colorAccent。

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/blue</item>
    <item name="colorPrimaryDark">@color/blue_dark</item>
    <item name="colorAccent">@color/blue_accent</item>
    <item name="customEditTextStyle">@style/CustomEditText</item>
</style>
<style name="CustomEditText" parent="Widget.AppCompat.EditText">
    <item name="colorPrimary">@color/blue</item>
    <item name="colorPrimaryDark">@color/blue_dark</item>
    <item name="colorAccent">@color/blue_accent</item>
</style>

editText 背景颜色工作正常,但是,我不能对自定义 editText 做同样的事情。

我试过使用这段代码,但它改变了整体状态,因此所有状态都使用相同的颜色。( https://stackoverflow.com/a/28433337 )

editText.getBackground().setColorFilter(getResources().getColor(R.color.your_color), PorterDuff.Mode.SRC_ATOP);

有没有办法在自定义 View 中应用 AppCompat 样式?这是 AppCompat 问题还是我在 CustomEditText 中做错了什么?任何想法将不胜感激。谢谢!

最佳答案

从 api 21 开始,您必须继承 AppCompatEdit 文本。所有支持的小部件也是如此。使用 AppCompat* 获取着色和其他支持的功能。

关于android - 使用 appcompat v7 自定义 EditText 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29807209/

相关文章:

android - 带有 subview 的自定义布局

android - Android compileTarget P appcompat库

android - 用于YouTube和Vimeo网址的正则表达式

java - 带有onclicklistener的android中的警报对话框

android - 使用 bindService 使 android 服务保持 Activity 状态

Android Maven 项目使用 Volley : NullPointerException

java - 如何在 Android 中创建动态颜色指示器?

android - 图像的光片?

android-appcompat - Android Studio-无法解析符号主题,原色,

java - Android: 包 android.support.v7.app.AlertDialog 不存在