自定义视图中的 Android 属性

use*_*504 5 android attributes themes android-custom-view

我有一个自定义的 android 视图类,除其他外,它会将大量文本直接绘制到提供给其 onDraw 覆盖的画布中。

我想做的是有一个属性,可以设置为“?android:attr / textAppearanceLarge”之类的东西,并选择常规文本设置而无需进一步设置样式。

在我的自定义视图的 attrs.xml 中,我有

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyView" >
        ...

        <attr name="textAppearance" format="reference" />

        ...
    </declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)

然后在 CustomView.java 中

final int[] bogus = new int[] { android.R.attr.textColor, android.R.attr.textSize, android.R.attr.typeface, android.R.attr.textStyle, android.R.attr.fontFamily };
final int ap = styledAttributes.getResourceId(com.test.R.styleable.MyView_textAppearance, -1);
final TypedArray textAppearance = ap != -1 ? context.obtainStyledAttributes(ap, bogus) : null;

if (textAppearance != null) {
    for (int i = 0; i < textAppearance.getIndexCount(); i++) {
        int attr = textAppearance.getIndex(i);

        switch (attr) {
        case android.R.attr.textColor:  textColor = textAppearance.getColor(attr, textColor); break;
        case android.R.attr.textSize:   textSize = textAppearance.getDimensionPixelSize(attr, textSize); break;
        case android.R.attr.typeface:   typefaceIndex = textAppearance.getInt(attr, typefaceIndex); break;
        case android.R.attr.textStyle:  textStyle = textAppearance.getInt(attr, textStyle);  break;
        case android.R.attr.fontFamily: fontFamily = textAppearance.getString(attr); break;         
        }
    }

    textAppearance.recycle();
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了开关变量、大小写常量等的各种变化,但最终我从未得到任何有用的东西。

我在这里做错了什么?

bly*_*roi 0

我认为你可以访问不同的资源:

com.test.R.styleable.MyView_textAppearance
Run Code Online (Sandbox Code Playgroud)

是你自己的,

android.R.attr.textColor
Run Code Online (Sandbox Code Playgroud)

其他的是Android的。

所以我设法让它定义我自己的属性:

    <com.test.TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        myns:textColor="@android:color/darker_gray" 
        myns:textSize="18sp"
        myns:textStyle="normal"/>
Run Code Online (Sandbox Code Playgroud)

和 attrs.xml:

<declare-styleable name="MyView_textAppearance">
    <attr name="textColor" format="reference|color" />

    <attr name="textSize" format="dimension" />
    <attr name="textStyle">
        <flag name="normal" value="0" />
        <flag name="bold" value="1" />
        <flag name="italic" value="2" />
    </attr>

</declare-styleable>
Run Code Online (Sandbox Code Playgroud)