-1

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

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

所以我可以更改按钮上显示的文本的字体?我只想更改按钮上的字体。我不想更改警报对话框中的字体。我只是不知道将代码放在哪里来更改按钮字体。我已经将自定义字体放置在 assets 中的“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();
    }

    }
4

2 回答 2

1

将您的代码放在onCreateActivity 中,setContentView如下所示:

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...
于 2013-01-06T19:58:33.413 回答
0
Button txt = (Button) findViewById(R.id.button1);  
Typeface font = Typeface.createFromAsset(getAssets(), "customfont.ttf");  
txt.setTypeface(font);

之内onCreate()

于 2013-01-06T19:58:41.087 回答