这是我所拥有的并且无法按预期工作
// some_color.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.example">
<item custom:greyShadow="true" android:color="@color/grey_shadow"/>
<item custom:blueShadow="true" android:color="@color/blue_shadow"/>
</selector>
“ greyShadow”和“ blueShadow”是我的自定义属性。
我如何使用它:
我想通过这样的样式在视图中使用它(颜色选择器some_color.xml):
布局:
// some_layout.xml
// the style text_input_style.xml sets a drawable as a background, that drawable uses color selector
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:blueShadow="true" <!-- this is the custom attribute -->
style="@style/text_input_style" <!-- this is the style -->
/>
风格:
// text_input_style.xml
<style name="text_input_style_blue">
<item name="android:background">@drawable/some_drawable.xml</item>
</style>
可绘制:
//some_drawable.xml (used by text_input_style.xml)
<item>
<shape android:shape="rectangle" >
<solid android:color="@color/some_color"/> <!-- here, the drawable uses the color selector -->
</shape>
</item>
这里发生了许多问题。
首先:Android中的标准视图(包括EditText)都不会识别或使用您定义的自定义属性。在您的布局中,custom:blueShadow="true"
EditText上的行是没有意义的。您将必须继承EditText的子类,自己读取属性,然后应用它们。
第二:您定义的属性用于可绘制的选择器,而不是视图,因此(至少对我而言)将它们应用于布局XML中的视图没有意义(至少对我而言)。通常,您可以通过子类化View并实现来使用此类属性onCreateDrawableState()
,然后refreshDrawableState
在视图内部状态的任何更改需要更新可绘制状态时调用。
public class CustomEditText extends EditText {
private boolean blueShadow;
private boolean greyShadow;
/* constructors omitted */
public void setBlueShadow(boolean b) {
if (blueShadow != b) {
blueShadow = b;
refreshDrawableState();
}
}
public void setGreyShadow(boolean b) {
if (greyShadow != b) {
greyShadow = b;
refreshDrawableState();
}
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
int[] baseState = super.onCreateDrawableState(extraSpace + 2);
if (blueShadow) {
mergeDrawableStates(baseState, new int[]{ R.attr.blueShadow });
}
if (greyShadow) {
mergeDrawableStates(baseState, new int[]{ R.attr.greyShadow });
}
}
}
这是有关自定义可绘制状态如何工作的很好指南:Charles Harley-Android中的自定义可绘制状态。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句