首页 > 解决方案 > 如何从 TextAppearance 获取字母间距

问题描述

我们正在使用一个包含所有样式的库,例如字母间距。这在我们的自定义视图中造成了一些问题,因为我们需要正确使用 TextAppearance。

我通过 XML 传递 TextAppearance 并尝试在油漆上使用它的属性。这适用于其他属性,例如文本大小和 FontTypeFace,但由于缺少textAppearanceSpan.getLetterSpacing()函数而不起作用。

XML 是通过声明的 styleable 传递的

attrs.xml

<declare-styleable name="MyCustomView">
    <attr name="TextAppearance" />
</declare-styleable>

布局.xml

<MyCustomView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:TextAppearance="?attr/TextAppearanceBig" />

然后我阅读了这些元素

MyCustomView.java

Paint mPaint;
public MyCustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, 0, 0);
    int textAppearanceID = typedArray.getResourceId(R.styleable.MyCustomView_TextApperance);
    TextAppearanceSpan textAppearanceSpan = new TextAppearanceSpan(context, textApperanceID);

    mPaint = new Paint();
    mPaint.setTextSize(textAppearanceSpan.getTextSize());
    mPaint.setTypeface(Typeface.create(textAppearanceSpan.getFamily(), Typeface.NORMAL);
}

@Override
protected synchronized void onDraw(Canvas canvas){
    canvas.drawText("Hello World", 0, 0, mPaint);
}

我想做,mPaint.setLetterSpacing(textAppearanceSpan.getLetterSpacing())但该功能textAppearanceSpan.getLetterSpacing()不存在。

标签: androidandroid-layout

解决方案


getLetterSpacing()是 Paint 类的方法,因此您可以将它与paint对象一起使用。

它的默认值为 0

setLetterSpacing (float letterSpacing)TextView

谢谢你。


推荐阅读