在自定义视图的Android特性

问题描述 投票:4回答:2

我有(其中包括)其他的事情将被直接借鉴了很多文本到提供给其的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>

然后在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();
}

我已经试过各种变化对开关变量,对此案常数等,我从来没有最终得到什么,甚至远程有用。

我在做什么错在这里?

android attributes themes android-custom-view
2个回答
0
投票

我想,您可以访问不同的资源:

com.test.R.styleable.MyView_textAppearance

是你自己的,

android.R.attr.textColor

和其他人是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"/>

和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>

0
投票

我知道这是一个老问题,但只是偶然到这个问题,这个解决方案为我工作:

在attrs.xml

<resources>
    <declare-styleable name="CustomView">
        ....
        <attr name="textAppearance" format="reference" />
    </declare-styleable>
</resources>

在CustomView.java

textAppearance = a.getResourceId(R.styleable.CustomView_textAppearance, -1);
TextViewCompat.setTextAppearance(textView, textAppearance);

然后在activity.xml

<CustomView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:textAppearance="?android:attr/textAppearanceMedium"
© www.soinside.com 2019 - 2024. All rights reserved.