将这行代码放在自定义按钮字体的哪里?

时间:2013-01-06 19:56:02

标签: java android xml button fonts

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

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

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

这是按钮的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();
    }

    }

2 个答案:

答案 0 :(得分:1)

将您的代码放在onCreate之后setContentView的{​​{1}}内:

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...

答案 1 :(得分:0)

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

onCreate()