有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在Android中设置和自定义不同的字体样式

I want to set different font style my ‘button’ text and ‘edit text box’ text like times New Roman, Calibri,Cambria and Georgia. How can i set different font,example for i want to change my login button text to Calibri font. I don't know how can i set or import font from MS Office or Font files. Please suggest me, Thank you..

MY XML CODE HERE

 <LinearLayout
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:orientation="vertical" >

    <EditText
        安卓:layout_width="match_parent"
        安卓:layout_height="wrap_content"
        安卓:hint="   User Name  " />

    <EditText
        安卓:layout_width="match_parent"
        安卓:layout_height="wrap_content"
        安卓:hint="   Password  " 
        安卓:fontFamily="Tekton Pro Ext"/>

    <Button
        安卓:layout_width="match_parent"
        安卓:layout_height="wrap_content"
        安卓:fontFamily="Tekton Pro Ext"
        安卓:text="   Login  " />
</LinearLayout>

Layout

enter image description here


共 (3) 个答案

  1. # 1 楼答案

    您需要在项目中的资产文件夹下创建字体文件夹,并将TTF放入其中。在主文件夹或活动中,您可以将字体设置为

    TextView myTextView=(TextView)findViewById(R.id.textBox);
    Typeface typeFace=Typeface.createFromAsset(getAssets(),"fonts/mytruetypefont.ttf");
    myTextView.setTypeface(typeFace);
    
  2. # 2 楼答案

    也许最好看看这些贴子,这些贴子正好回答了您的需求:

    1-How to change fontFamily of TextView in Android

    2-How to change the font on the TextView?

    简言之,你必须这样做: 将字体放在/fonts目录下的资产文件夹中,然后使用以下代码行:

    Button bt = (Button) findViewById(R.id.myButton);
    Typeface face = Typeface.createFromAsset(getAssets(),
                "fonts/epimodem.ttf");
    bt.setTypeface(face);
    
  3. # 3 楼答案

    以上所有答案都是正确的。如果您想在整个应用程序中使用具有不同字体的ButtonTextView,请执行以下操作

    public class FontsArePriceyTextView extends TextView {
    
        public MyTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            setCostlyFont();
        }
    
        public MyTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            setCostlyFont();
        }
    
        public MyTextView(Context context) {
            super(context);
            setCostlyFont();
        }
    
        private void setCostlyFont() {
            if (!isInEditMode()) {
                Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "filenameofyourfont.ttf");
                setTypeface(tf);
            }
        }
    }
    

    然后在布局中,将TextView替换为yourpackagename.FontsArePriceyTextView。例如

    <com.company.projectname.widgets.FontsArePriceyTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Your awesome stylised text" />
    

    你该走了