【问题标题】:Where to put this line of code for custom button font? [closed]自定义按钮字体的这行代码放在哪里? [关闭]
【发布时间】:2013-01-06 19:56:02
【问题描述】:

我应该把这段代码放在哪里

 Button txt = (Button) findViewById(R.id.button1);  
    Typeface font = Typeface.createFromAsset(getAssets(), "customfont.ttf");  
    txt.setTypeface(font);

所以我可以更改按钮上显示的文本的字体? 我只想更改按钮上的字体。我不想更改警报对话框中的字体。我只是不知道将代码放在哪里来更改按钮字体。我已经将自定义字体放置在资产中的“字体”文件夹中。

这里是按钮的xml部分:

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:onClick="alertBtn"
    android:text="Click for message" 
    android:textSize="22sp"
    />

这是我项目的代码:

package com.test.hellothere;

import android.app.Activity;
import android.app.AlertDialog;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class HelloThereActivity extends Activity implements View.OnClickListener{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


    }

    public void onClick(View v){}

    public void alertBtn(View v){

        new AlertDialog.Builder(this)
        .setTitle("Hello")
        .setMessage("Hello There!")
        .setNeutralButton("Go Back", null)
        .show();
    }

    }

【问题讨论】:

  • setContentView();之后
  • 如果字体在子文件夹下,则应在路径中引用,即Typeface.createFromAsset(getAssets(), "fonts/customfont.ttf")

标签: java android xml button fonts


【解决方案1】:

将您的代码放在setContentView 之后的Activity 的onCreate 中:

public class HelloThereActivity extends Activity implements View.OnClickListener{
    /** Called when the activity is first created. */
 Button txt;
 Typeface font;
  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       txt = (Button) findViewById(R.id.button1);  

       // call here for setting font 
       setfonttoView(txt);

       //.....same for other buttons
    }
  public void setfonttoView(Button button){
       font = Typeface.createFromAsset(getAssets(), "customfont.ttf");  
       button.setTypeface(font);
    }

  //your code here...

【讨论】:

  • 谢谢,还有没有办法一次设置多个按钮的字体,这样我就不必一遍又一遍地重新输入代码,也为了整洁?
  • @CaptnBuzz :只需在同一个类中创建一个方法并将按钮实例作为参数传递给它,以将字体设置为多个按钮
  • 你能给我举个例子吗?抱歉所有问题
  • @CaptnBuzz :查看我的编辑答案
  • 非常感谢你教会了我很多东西哈哈 :)
【解决方案2】:
Button txt = (Button) findViewById(R.id.button1);  
Typeface font = Typeface.createFromAsset(getAssets(), "customfont.ttf");  
txt.setTypeface(font);

onCreate()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-21
    • 2014-01-04
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2013-01-20
    相关资源
    最近更新 更多