Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/220.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何更改按钮后的字体';是否已将添加到视图组?_Android_Android Button_Android Styles_Android Fonts_Android Typeface - Fatal编程技术网

Android 如何更改按钮后的字体';是否已将添加到视图组?

Android 如何更改按钮后的字体';是否已将添加到视图组?,android,android-button,android-styles,android-fonts,android-typeface,Android,Android Button,Android Styles,Android Fonts,Android Typeface,给定运行时创建的按钮: Button button = Button(context) 设置自定义字体的方法是: button.setTypeface(myTypeface) 但是,我发现它只在我将其添加到视图组之前起作用,而在添加到视图组之后不起作用 我也试过: button.setTypeface(myTypeface, myStyle) 但它也不起作用。我需要动态更改我的按钮字体。我尝试了invalidate()和requestLayout(),但字体从未改变。解决方案:-您可以使

给定运行时创建的
按钮

Button button = Button(context)
设置自定义字体的方法是:

button.setTypeface(myTypeface)
但是,我发现它只在我将其添加到
视图组之前起作用,而在添加到
视图组之后不起作用

我也试过:

button.setTypeface(myTypeface, myStyle) 

但它也不起作用。我需要动态更改我的
按钮
字体。我尝试了
invalidate()
requestLayout()
,但字体从未改变。

解决方案:-您可以使用自定义字体对Button类进行子类化,并使用它代替Button。

public class MyButton extends AppCompatButton {

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

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

    public MyButton(Context context) {
        super(context);
        init();
    }

    private void init() {
        if (!isInEditMode()) {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font.ttf");
            setTypeface(tf);
        }
    }
}

很抱歉,正如我所说,我的问题是在将其添加到视图组后无法更改它