2

我已阅读并理解https://stackoverflow.com/a/5052401/305532,但是我想要的不是一般样式和覆盖单个小部件样式,而是作为子小部件一部分的样式。

说,我有一个RelativeLayout由标准EditText和标准组成的化合物Button。我可以覆盖android:buttonStyle这个样式Button,但我真正想要的是

<my.custom.Widget
  ...
  pkg:buttonStyle="@style/CustomStyle" />

其中 theCustomStyle可以派生自android:style/Widget.Button,但对于 的每个实例都是可变的,my.custom.Widget因为pkg:buttonStyle

我知道的唯一选择是将所有可样式化的属性单独添加到我attrs.xml的中(如果两个或多个子小部件需要相同的属性但具有不同的值,通常会发生冲突),然后手动复制/设置所有这些属性在my.custom.Widget' s 构造函数/init 方法。

有没有办法做到这一点?

4

2 回答 2

2

不幸的是,这似乎是不可能的。我能找到的唯一类似的例子是ActionBar:您可以为标题、副标题和进度指示器传递样式。查看 的源代码ActionBarView,标题和副标题TextView的样式与setTextAppearance(). 该类有一个额外ProgressBar构造函数,它接受样式的第四个参数。由于大多数View类没有这个额外的构造函数,因此不可能将样式传递给它们。但是,有几种选择:

  1. 传递子视图的布局而不是样式并在您的小部件中膨胀它。
  2. 如果子视图是TextView(as Buttonand EditTextare)的子视图,则setTextAppearance()用于传递的样式。这将为文本应用大量样式。如果您想允许用户应用其他样式,例如背景或填充,您仍然需要为每个样式添加自定义属性。如果您正在制作复合小部件,则用户很有可能不需要将所有可能的样式应用于子视图,因此仅公开一个子集可能就足够了。
  3. 正如您已经提到的,添加主题范围的样式。
于 2014-10-17T15:19:09.317 回答
1

在自定义视图中使用内置小部件样式

如果您创建一个作为 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

于 2013-12-28T01:30:10.420 回答