在自定义视图中使用内置小部件样式
如果您创建一个作为 Android 小部件子类的自定义视图并希望使用内置的 Android 小部件样式对其进行样式设置,那么您必须实现以下结构。
更改您的自定义View
以从 Android Widget 样式继承其属性
CustomTextView.java
public class CustomTextView extends TextView {
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray styledAttrs = context.obtainStyledAttributes(attrs,
R.styleable.CustomTextView, R.attr.customImageButtonStyle, 0);
String fontName = styledAttrs.getString(
R.styleable.CustomTextView_customTypeface);
styledAttrs.recycle();
// Use custom attribute to do something...
}
}
的defStyleAttr
参数Context#obtainStyledAttributes()
是您指定对要继承的样式的引用的位置。在此示例中,您使用R.attr.customImageButtonStyle
. themes.xml
您在和中定义这些资源styles.xml
。
主题.xml
<resources>
<style name="AppTheme">
<!--Define a theme-wide customTextViewStyle -->
<item name="customTextViewStyle">@style/Widget.TextView</item>
</style>
</resources>
样式.xml
<resources>
<style name="Widget.TextView"
parent="@android:style/Widget.TextView">
<item name="customTypeface">custom_font_typeface</item>
</style>
</resources>
attrs.xml
<resources>
<declare-styleable name="CustomTextView">
<attr name="customTypeface" format="string" />
</declare-styleable>
<declare-styleable name="CustomTheme">
<attr name="customTextViewStyle" format="reference"/>
</declare-styleable>
</resources>
*活动布局*
<com.packagename.ui.view.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bacon ipsum" />
CustomTextView
不再需要您定义样式或customTypeface
属性,它已经在主题范围customTextViewStyle
内定义themes.xml
。