简体   繁体   中英

Android Custom Button Font

<Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="alertBtn1"
        android:text="Hello" 
        android:textSize="22sp"

Above is the code for the button in the xml, and I the custom font in a folder "fonts" in the assets folder. How can I change the font of the button to match the custom font I have?

Here is what the button does:

public void onClick(View v){}

public void alertBtn(View v){

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

I tried using

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

but it said R.id.custom_font); cannot be resolved or is not a field, and that there is a syntax error at font in txt.setTypeface(font);

Button txt = (Button) findViewById(R.id.custom_font);

Should be

Button txt = (Button) findViewById(R.id.button1);

OR android:id="@+id/button1"

should be

android:id="@+id/custom_font"

That will fix your cannot be resolved error, but I don't see the syntax error in the setTypeface line.

Change

Button txt = (Button) findViewById(R.id.custom_font);

to

Button txt = (Button) findViewById(R.id.button1);

and android:onClick="alertBtn1" to android:onClick="alertBtn" becuase you are setting alertBtn1 in Button xml and in code part you have method with alertBtn name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM