我创建了一个扩展 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/