繁体   English   中英

Android Studio:在“自定义”扩展活动上更改textSize

[英]Android studio: change textSize on Custom extends activity

我将TextView类扩展为“ CustomTextView”,这就是为什么我需要设置自定义字体的原因。 结果如下:

public class CustomTextView extends TextView {

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/nn.otf"));
        this.setTextSize(30);
    }
}

您可以看到我将默认的textSize设置为30:

当我想要这个CustomTextView时,可以使用以下代码:

<com.calendar.CustomTextView
    android:id="@+id/edData"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="DOM 21 GIU"
    android:textSize="45dp"/>

如果您注意到了,我将textSize值设置为45dp,但它仍然是30(来自自定义类)。 如何设置不同的textSize? 还有,想要大胆的风格吗?

您应该删除this.setTextSize(30); 从构造函数中获取,因为xml布局会在super(context,attrs)调用期间进行大小调整,并且otf文件中应包含粗体字体(通常是不同样式的不同otf文件)

这是我的解决方案:(我使用textColor而不是textSize进行了测试,但这是相同的)。

我编辑了res / values / atrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomTextView">
        <attr name="textColor" format="string" />
    </declare-styleable>
</resources>

然后,我按如下方式编辑课程:

public class CustomTextView extends TextView {

    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
    }

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

    public CustomTextView(Context context) {
        super(context);
        init(null);
    }

private void init(AttributeSet attrs) {
    if (attrs != null) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.CustomTextView);
        String fontName = a.getString(R.styleable.CustomTextView_fontName);

        if (textColor != null) {
            this.setTextColor(Color.parseColor(textColor));
        } else {
            this.setTextColor(Color.parseColor("#000000"));
        }

        a.recycle();
    }
   }

}

所以这项工作:

 <com.imgspa.listviewadapter.CustomTextView
        android:id="@+id/ed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            listviewadapter:textColor="#FF0000"/>

        <com.imgspa.listviewadapter.CustomTextView
            android:id="@+id/edRis"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="35dp" />

第一个自定义textview文本为红色,第二个为黑色

要设置样式,只需使用android:textStyle="bold" 对于您的其他问题,可以使用attrs.getAttribute(NAME OF ATTRIBUTE)方法从我认为的属性中检查textSize,然后将其设置为该值或根据需要将其设置为30。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM