Java 使用字体更改按钮文本字体

Java 使用字体更改按钮文本字体,java,android,Java,Android,我正在尝试更改onCreate()方法中所有按钮的字体 有办法吗 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Typeface buttontypeface = Typeface.createFromAsset(getAssets(),"Calculator.t

我正在尝试更改
onCreate()
方法中所有按钮的字体 有办法吗

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Typeface buttontypeface = Typeface.createFromAsset(getAssets(),"Calculator.ttf");
    // get just buttons ids
}
如果我使用
findViewById
我将获得单个按钮的id,我需要一种快速的方法来获取所有按钮id,然后更改它们的字体。 我有:
button1,buttona,buttonout

它可能会帮助你

    Button button= (Button) findViewById(R.id.button1);
    Typeface face8 = Typeface.createFromAsset(getApplicationContext().getAssets(), "MyFont.ttf");
    button.setTypeface(face8);
此问题:显示如何为
TextView
s实现此功能

如果要对按钮执行相同的操作,请使用以下代码:

private void overrideFonts(final Context context, final View v) {
try {
    if (v instanceof ViewGroup) {
        ViewGroup vg = (ViewGroup) v;
        for (int i = 0; i < vg.getChildCount(); i++) {
            View child = vg.getChildAt(i);
            overrideFonts(context, child);
     }
    } else if (v instanceof Button ) {
        ((Button) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "font.ttf"));
    }
} catch (Exception e) {
}
}
private void覆盖(最终上下文,最终视图v){
试一试{
if(视图组的v实例){
视图组vg=(视图组)v;
对于(int i=0;i
此代码的所有学分归Agarwal Shankar所有


至于参数:对于
上下文
您可能想要使用
,对于
v
您想要使用父视图
,这通常是上部的
布局
属性(
线性布局
或您正在使用的任何属性)

首先获取布局中的所有按钮,然后更改每个人的字体,假设viewGroup是您的根视图(可以是RelativeLayout、LinearLayout等)

int count=viewGroup.getChildCount();
for(int i=0;i

您可以通过在xml文件中为根视图指定一个if来获取它。

您可以创建这样一个简单的方法

private void typefaces(int... args){
    Typeface buttontypeface = Typeface.createFromAsset(getAssets(), "Calculator.ttf");
    for(int i = 0; i < args.length; i++){
        ((Button) findViewById(args[i])).setTypeface(buttontypeface);
    }
}

其中
R.id.button、R.id.button1、R.id.button2、R.id.button3
是4个按钮的id。您可以添加任意数量的按钮

如果我有10个按钮,那么我会为每个按钮添加findViewById,我想要一种快速的方法,此代码只会更改按钮的字体1,我想更改所有按钮的字体,我不想在搜索时执行10次这样的操作,你可以复制并粘贴10次,伙计!:-Plol我只是相信他们的方法很简单,没有复制和过去10次:pgetChildAt(i)不能从静态上下文引用,我不能在ViewGroupno上使用getChildAt(i),在您正在使用的实例上使用getChildAt(i),而不是在类的名称上。这可能会起作用,但我想在onCreate()上使用Viewgroup方法不在我需要创建它的方法上,我可以这样做吗?当然!只需将上述方法粘贴到Activity类中的任意位置,然后从
onCreate()
调用此方法即可。
private void typefaces(int... args){
    Typeface buttontypeface = Typeface.createFromAsset(getAssets(), "Calculator.ttf");
    for(int i = 0; i < args.length; i++){
        ((Button) findViewById(args[i])).setTypeface(buttontypeface);
    }
}
typefaces(R.id.button, R.id.button1, R.id.button2, R.id.button3);