Android 如何从自定义视图传递样式属性?

Android 如何从自定义视图传递样式属性?,android,Android,我正在创建一个自定义文本切换器,如下所示 public class CustomTextSwitcher extends TextSwitcher { private static final long SHOW_TEXT_ANIMATION_TIME = 100; public CustomTextSwitcher(Context context, AttributeSet attrs) { super(context, attrs); ini

我正在创建一个自定义文本切换器,如下所示

public class CustomTextSwitcher extends TextSwitcher {
    private static final long SHOW_TEXT_ANIMATION_TIME = 100;

    public CustomTextSwitcher(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        Animation in = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);
        Animation out = AnimationUtils.loadAnimation(context, android.R.anim.fade_out);

        in.setDuration(SHOW_TEXT_ANIMATION_TIME);
        out.setDuration(SHOW_TEXT_ANIMATION_TIME);

        this.setInAnimation(in);
        this.setOutAnimation(out);
    }

    public void setStyle(final int style) {
        this.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                return new TextView(new ContextThemeWrapper(context, style),
                        null, 0);
            }
        });

    }
}
这很好,只是我需要在初始化后使用上面声明的
setStyle
函数显式设置样式

我希望我不需要调用
setStyle
,只需要用XML声明我的样式(如下面的代码所示),通过构造函数中的
attr
值获得int值,并将其发送到
ViewFacory
,所有操作都在
init()
函数中完成

<my.example.CustomTextSwitcher
    android:id="@+id/search_list_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="@style/recentSearchHeaderText" />


如何实现这一点?

从构造函数获得的
属性集
是从XML中的
样式
属性以及提供的其他属性生成的。因此,您只需保存它,然后在中传递它。
setStyle
方法实际上可以与接受样式ID的方法一起使用。它将只查看与
TextView
关联的样式属性。我想说,这比通过属性集进行解析并创建自己的样式更容易

我找到了这样做的方法。它就像
attrs.getStyleAttribute()
一样简单。下面显示了代码

public class CustomTextSwitcher extends TextSwitcher {
    private static final long SHOW_TEXT_ANIMATION_TIME = 100;

    public CustomTextSwitcher(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    private void init(AttributeSet attrs) {

        this.setFactory(new ViewFactory() {
            @Override
            public View makeView() {
                return new TextView(new ContextThemeWrapper(context, 
                        attrs.getStyleAttribute()), null, 0);
            }
        });
        Animation in = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);
        Animation out = AnimationUtils.loadAnimation(context, android.R.anim.fade_out);

        in.setDuration(SHOW_TEXT_ANIMATION_TIME);
        out.setDuration(SHOW_TEXT_ANIMATION_TIME);

        this.setInAnimation(in);
        this.setOutAnimation(out);
    }
}