Android 如何在不使用“样式”属性的情况下设置自定义视图的样式?

Android 如何在不使用“样式”属性的情况下设置自定义视图的样式?,android,Android,我通过所有给定的构造函数传递样式引用: public MyCustomView(Context context) { super(context, null, R.style.MyStyle); } public MyCustomView(Context context, AttributeSet attrs) { super(context, attrs, R.style.MyStyle); } public MyCustomView(Context context, At

我通过所有给定的构造函数传递样式引用:

public MyCustomView(Context context)
{ 
    super(context, null, R.style.MyStyle);
}
public MyCustomView(Context context, AttributeSet attrs)
{ 
    super(context, attrs, R.style.MyStyle);
}
public MyCustomView(Context context, AttributeSet attrs, int defStyle)
{ 
    super(context, attrs, R.style.MyStyle);
}

我在棉花糖上试这个。样式未应用,但通过样式属性应用时有效。

尝试使用三参数构造函数和ContextThemeWrapper,如下所示:

MyCustomView mView = new MyCustomView(new ContextThemeWrapper(this,R.style.yourStyle),null,0);
    public MyCustomView(Context context, AttributeSet attrs, int defStyle)
{ 
    super(context, attrs, defStyle);
}
而MyCustomView类的构造函数如下所示:

MyCustomView mView = new MyCustomView(new ContextThemeWrapper(this,R.style.yourStyle),null,0);
    public MyCustomView(Context context, AttributeSet attrs, int defStyle)
{ 
    super(context, attrs, defStyle);
}

这应该是可行的。

据我所知,有4个而不是3个ViewConstructor不是应该有
super
而不是
This
,但是如何通过xml实现呢?您可以通过为活动或应用程序的主题属性指定自定义样式来覆盖它们,并应用于整个活动或应用程序,但如果您愿意的话在xml中设置单个视图的样式我认为这是通过xml(通过设置样式属性)实现的唯一方法。这也是有道理的,没有人会需要一种方法来做像这样的事情。