【问题标题】:How to set custom textStyle in a class?如何在类中设置自定义 textStyle?
【发布时间】:2019-07-09 12:34:15
【问题描述】:

我正在创建一个类并设置文本样式。我已经在 attrs 和 styleable 和 style 中定义了 getter setter 和 set textStyle bold 仍然文本没有变粗。如何设置粗体字?请帮忙?

 <declare-styleable name="CustomTagGroup"> 
        <attr name="descriptionTextStyle" format="flags">
            <flag name="normal" value="0" />
            <flag name="bold" value="1" />
            <flag name="italic" value="2" />
            <flag name="bolditalic" value="3" />
        </attr>

    <style name="CustomTagGroup">
  <item name="atg_horizontalPadding">12dp</item>
        <item name="atg_verticalPadding">3dp</item>
        <item name="android:textStyle">bold</item>
        <item name="descriptionTextStyle">bolditalic</item>
    </style>

  final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomTagGroup, defStyleAttr, R.style.CustomTagGroup);
        try {
a.getType(R.styleable.CustomTagGroup_descriptionTextStyle);
            int bold = Typeface.BOLD_ITALIC;
            textStyle = a.getInt(R.styleable.CustomTagGroup_descriptionTextStyle, bold);
}catch(Exception e){
e.printStackTrace()
}

【问题讨论】:

    标签: android styles


    【解决方案1】:

    这是您扩展 TextView 的自定义类吗? 如果是,那么首先获取您在 xml 中定义的属性,例如:

    <com.package.CustomTextView
     ......
     app:text_style = "1"
    />
    

    获取属性值后通过下面的代码添加setBold

    @Override
        protected void onFinishInflate() {
            super.onFinishInflate();
            // set your if else condition that come from attr
            // Like you get 1 then execute below line
            this.setTypeface(getTypeface(),Typeface.BOLD);
        }
    

    【讨论】:

    • 我的自定义类扩展了 ViewGroup。请建议另一种方法,因为它不适合我。
    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多