วิธีการเปลี่ยนแบบอักษรใน a TextViewเป็นค่าเริ่มต้นมันจะปรากฏเป็น Arial? จะเปลี่ยนเป็นHelveticaอย่างไร
วิธีการเปลี่ยนแบบอักษรใน a TextViewเป็นค่าเริ่มต้นมันจะปรากฏเป็น Arial? จะเปลี่ยนเป็นHelveticaอย่างไร
คำตอบ:
ก่อนอื่นค่าเริ่มต้นไม่ใช่ Arial ค่าเริ่มต้นคือ Droid Sans
ประการที่สองเพื่อเปลี่ยนเป็นฟอนต์ในตัวแบบอื่นให้ใช้android:typefaceในเลย์เอาต์ XML หรือsetTypeface()ใน Java
ประการที่สามไม่มีตัวอักษร Helvetica ใน Android ตัวเลือกในตัว ได้แก่ Droid Sans ( sans), Droid Sans Mono ( monospace) และ Droid Serif ( serif) ในขณะที่คุณสามารถรวมฟอนต์ของคุณเองกับแอปพลิเคชันของคุณและใช้มันผ่านทางsetTypeface()โปรดจำไว้ว่าไฟล์ฟอนต์มีขนาดใหญ่และในบางกรณีจำเป็นต้องมีข้อตกลงสิทธิ์ใช้งาน (เช่นHelvetica, ฟอนต์ Linotype )
แก้ไข
ภาษาการออกแบบ Android นั้นอาศัยเครื่องมือการพิมพ์แบบดั้งเดิมเช่นขนาดพื้นที่จังหวะและการจัดแนวด้วยกริดพื้นฐาน การปรับใช้เครื่องมือเหล่านี้ให้ประสบความสำเร็จเป็นสิ่งจำเป็นเพื่อช่วยให้ผู้ใช้เข้าใจหน้าจอข้อมูลได้อย่างรวดเร็ว เพื่อสนับสนุนการใช้งานพิมพ์เช่น Ice Cream Sandwich ได้เปิดตัวตระกูล Roboto ใหม่ซึ่งได้รับการสร้างขึ้นเป็นพิเศษสำหรับความต้องการของ UI และหน้าจอความละเอียดสูง
เฟรมเวิร์ก TextView ปัจจุบันให้ Roboto ด้วยน้ำหนักแบบบางน้ำหนักเบาปกติและหนารวมถึงสไตล์ตัวเอียงสำหรับน้ำหนักแต่ละตัว เฟรมเวิร์กยังเสนอตัวแปรโรโบโต้แบบย่อในน้ำหนักแบบปกติและแบบหนาพร้อมกับสไตล์ตัวเอียงสำหรับน้ำหนักแต่ละตัว
หลังจาก ICS แล้ว Android จะรวมสไตล์ของแบบอักษร Roboto, อ่านเพิ่มเติมRoboto
แก้ไข 2
ด้วยการถือกำเนิดของ Support Library 26 ตอนนี้ Android รองรับแบบอักษรที่กำหนดเองตามค่าเริ่มต้น คุณสามารถแทรกแบบอักษรใหม่ในres / แบบอักษรซึ่งสามารถตั้งค่าเป็น TextViews ทีละรายการใน XML หรือโดยทางโปรแกรม ฟอนต์เริ่มต้นสำหรับแอปพลิเคชันทั้งหมดสามารถเปลี่ยนแปลงได้โดยกำหนดเป็นสไตล์.xmlเอกสารประกอบสำหรับนักพัฒนา android มีคำแนะนำที่ชัดเจนเกี่ยวกับเรื่องนี้ที่นี่
ขั้นแรกให้ดาวน์โหลด.ttfไฟล์ของแบบอักษรที่คุณต้องการ ( arial.ttf) วางไว้ใน   assets  โฟลเดอร์ (โฟลเดอร์ทรัพย์สินภายในสร้างโฟลเดอร์ใหม่ชื่อแบบอักษรและวางไว้ข้างใน) ใช้รหัสต่อไปนี้เพื่อใช้แบบอักษรกับคุณTextView:
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/arial.ttf"); 
textView.setTypeface(type);
              Typeface tf = Typeface.createFromAsset(getAssets(),
        "fonts/DroidSansFallback.ttf");
TextView tv = (TextView) findViewById(R.id.CustomFontText);
tv.setTypeface(tf);
              คุณอาจต้องการสร้างคลาสแบบคงที่ซึ่งจะมีแบบอักษรทั้งหมด ด้วยวิธีนี้คุณจะไม่สร้างแบบอักษรหลายครั้งซึ่งอาจส่งผลเสียต่อประสิทธิภาพการทำงาน เพียงตรวจสอบให้แน่ใจว่าคุณสร้างโฟลเดอร์ย่อยที่เรียกว่า " แบบอักษร " ภายใต้โฟลเดอร์ " สินทรัพย์ "
ทำสิ่งที่ชอบ:
public class CustomFontsLoader {
public static final int FONT_NAME_1 =   0;
public static final int FONT_NAME_2 =   1;
public static final int FONT_NAME_3 =   2;
private static final int NUM_OF_CUSTOM_FONTS = 3;
private static boolean fontsLoaded = false;
private static Typeface[] fonts = new Typeface[3];
private static String[] fontPath = {
    "fonts/FONT_NAME_1.ttf",
    "fonts/FONT_NAME_2.ttf",
    "fonts/FONT_NAME_3.ttf"
};
/**
 * Returns a loaded custom font based on it's identifier. 
 * 
 * @param context - the current context
 * @param fontIdentifier = the identifier of the requested font
 * 
 * @return Typeface object of the requested font.
 */
public static Typeface getTypeface(Context context, int fontIdentifier) {
    if (!fontsLoaded) {
        loadFonts(context);
    }
    return fonts[fontIdentifier];
}
private static void loadFonts(Context context) {
    for (int i = 0; i < NUM_OF_CUSTOM_FONTS; i++) {
        fonts[i] = Typeface.createFromAsset(context.getAssets(), fontPath[i]);
    }
    fontsLoaded = true;
}
}
ด้วยวิธีนี้คุณสามารถรับแบบอักษรได้จากทุกที่ในแอปพลิเคชันของคุณ
TextViewPlus.java:
public class TextViewPlus extends TextView {
    private static final String TAG = "TextView";
    public TextViewPlus(Context context) {
        super(context);
    }
    public TextViewPlus(Context context, AttributeSet attrs) {
        super(context, attrs);
        setCustomFont(context, attrs);
    }
    public TextViewPlus(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setCustomFont(context, attrs);
    }
    private void setCustomFont(Context ctx, AttributeSet attrs) {
        TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
        String customFont = a.getString(R.styleable.TextViewPlus_customFont);
        setCustomFont(ctx, customFont);
        a.recycle();
    }
    public boolean setCustomFont(Context ctx, String asset) {
        Typeface typeface = null;
        try {
            typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
        } catch (Exception e) {
            Log.e(TAG, "Unable to load typeface: "+e.getMessage());
            return false;
        }
        setTypeface(typeface);
        return true;
    }
}
attrs.xml: (ตำแหน่งที่จะวางres / values )
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TextViewPlus">
        <attr name="customFont" format="string"/>
    </declare-styleable>
</resources>
วิธีใช้:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:foo="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <com.mypackage.TextViewPlus
        android:id="@+id/textViewPlus1"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:text="@string/showingOffTheNewTypeface"
        foo:customFont="my_font_name_regular.otf">
    </com.mypackage.TextViewPlus>
</LinearLayout>
หวังว่านี่จะช่วยคุณได้
คำตอบข้างต้นถูกต้อง เพียงตรวจสอบให้แน่ใจว่าคุณสร้างโฟลเดอร์ย่อยที่เรียกว่า "แบบอักษร" ใต้ "ทรัพย์สิน" หากคุณใช้รหัสนั้น
อีกวิธีในการรวมการสร้างแบบอักษร ...
public class Font {
  public static final Font  PROXIMA_NOVA    = new Font("ProximaNovaRegular.otf");
  public static final Font  FRANKLIN_GOTHIC = new Font("FranklinGothicURWBoo.ttf");
  private final String      assetName;
  private volatile Typeface typeface;
  private Font(String assetName) {
    this.assetName = assetName;
  }
  public void apply(Context context, TextView textView) {
    if (typeface == null) {
      synchronized (this) {
        if (typeface == null) {
          typeface = Typeface.createFromAsset(context.getAssets(), assetName);
        }
      }
    }
    textView.setTypeface(typeface);
  }
}
และเพื่อใช้ในกิจกรรมของคุณ ...
myTextView = (TextView) findViewById(R.id.myTextView);
Font.PROXIMA_NOVA.apply(this, myTextView);
โปรดทราบว่าสำนวนการล็อคที่มีการตรวจสอบซ้ำสองครั้งนี้จะมีการทำงานอย่างถูกต้องกับรุ่นหน่วยความจำที่ใช้ใน Java 1.5+
ขั้นตอนที่ 1: เพิ่มไฟล์ตัวอักษร
ตัวอย่างเช่นเมื่อไฟล์ฟอนต์จะเป็น helvetica_neue.ttf ที่จะสร้าง R.font.helvetica_neue
ขั้นตอนที่ 2: สร้างตระกูลแบบอักษร
ตัวอย่างเช่น:
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/helvetica_neue" />
</font-family>
ขั้นตอนที่ 3: ใช้
ในรูปแบบ xml:
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/my_font"/>
หรือเพิ่มแบบอักษรในสไตล์:
<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
    <item name="android:fontFamily">@font/lobster</item>
</style>
สำหรับตัวอย่างเพิ่มเติมคุณสามารถทำตามเอกสาร:
มันเก่าไปหน่อย แต่ฉันปรับปรุง CustomFontLoader ของชั้นหน่อยแล้วฉันก็อยากจะแบ่งปันมันดังนั้นมันจึงมีประโยชน์ เพียงแค่สร้างคลาสใหม่ด้วยรหัสนี้
 import android.content.Context;
 import android.graphics.Typeface;
public enum FontLoader {
ARIAL("arial"),
TIMES("times"),
VERDANA("verdana"),
TREBUCHET("trbuchet"),
GEORGIA("georgia"),
GENEVA("geneva"),
SANS("sans"),
COURIER("courier"),
TAHOMA("tahoma"),
LUCIDA("lucida");   
private final String name;
private Typeface typeFace;
private FontLoader(final String name) {
    this.name = name;
    typeFace=null;  
}
public static Typeface getTypeFace(Context context,String name){
    try {
        FontLoader item=FontLoader.valueOf(name.toUpperCase(Locale.getDefault()));
        if(item.typeFace==null){                
            item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");                 
        }           
        return item.typeFace;
    } catch (Exception e) {         
        return null;
    }                   
}
public static Typeface getTypeFace(Context context,int id){
    FontLoader myArray[]= FontLoader.values();
    if(!(id<myArray.length)){           
        return null;
    } 
    try {
        if(myArray[id].typeFace==null){     
            myArray[id].typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+myArray[id].name+".ttf");                       
        }       
        return myArray[id].typeFace;    
    }catch (Exception e) {          
        return null;
    }   
}
public static Typeface getTypeFaceByName(Context context,String name){      
    for(FontLoader item: FontLoader.values()){              
        if(name.equalsIgnoreCase(item.name)){
            if(item.typeFace==null){
                try{
                    item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");     
                }catch (Exception e) {          
                    return null;
                }   
            }
            return item.typeFace;
        }               
    }
    return null;
}   
public static void loadAllFonts(Context context){       
    for(FontLoader item: FontLoader.values()){              
        if(item.typeFace==null){
            try{
                item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");     
            }catch (Exception e) {
                item.typeFace=null;
            }   
        }                
    }       
}   
}
จากนั้นใช้โค้ดนี้กับข้อความที่คุณดู:
 Typeface typeFace=FontLoader.getTypeFace(context,"arial");  
 if(typeFace!=null) myTextView.setTypeface(typeFace);
              ในที่สุดฉันก็ได้คำตอบที่ง่ายมากสำหรับเรื่องนี้
ใช้ห้องสมุดการสนับสนุนเหล่านี้ในระดับแอป gradle ,
compile 'com.android.support:appcompat-v7:26.0.2'
compile 'com.android.support:support-v4:26.0.2'จากนั้นสร้างไดเรกทอรีชื่อ"font"ภายในโฟลเดอร์res
หลังจากนั้นอ้างอิงแบบอักษรนั้นจากxmlเช่นนี้
        <Button
        android:id="@+id/btn_choose_employee"
        android:layout_width="140dp"
        android:layout_height="40dp"
        android:layout_centerInParent="true"
        android:background="@drawable/rounded_red_btn"
        android:onClick="btnEmployeeClickedAction"
        android:text="@string/searching_jobs"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:fontFamily="@font/times_new_roman_test"
        />ในตัวอย่างนี้times_new_roman_testเป็นไฟล์ฟอนต์ ttf จากไดเร็กทอรีฟอนต์นั้น
import java.lang.ref.WeakReference;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Typeface;
public class FontsManager {
    private static FontsManager instance;
    private static HashMap<String, WeakReference<Typeface>> typefaces = new HashMap<String, WeakReference<Typeface>>();
    private static Context context;
    private FontsManager(final Context ctx) {
        if (context == null) {
            context = ctx;
        }
    }
    public static FontsManager getInstance(final Context appContext) {
        if (instance == null) {
            instance = new FontsManager(appContext);
        }
        return instance;
    }
    public static FontsManager getInstance() {
        if (instance == null) {
            throw new RuntimeException(
                    "Call getInstance(Context context) at least once to init the singleton properly");
        }
        return instance;
    }
    public Typeface getFont(final String assetName) {
        final WeakReference<Typeface> tfReference = typefaces.get(assetName);
        if (tfReference == null || tfReference.get() == null) {
            final Typeface tf = Typeface.createFromAsset(context.getResources().getAssets(),
                    assetName);
            typefaces.put(assetName, new WeakReference<Typeface>(tf));
            return tf;
        }
        return tfReference.get();
    }
}
ด้วยวิธีนี้คุณสามารถสร้างมุมมองที่สืบทอดจาก TextView และการเรียก setTypeface บนตัวสร้าง
เมื่อตัวอักษรของคุณถูกเก็บไว้ภายในres/asset/fonts/Helvetica.ttfใช้ต่อไปนี้:
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/Helvetica.ttf"); 
txt.setTypeface(tf);
หรือหากไฟล์ฟอนต์ของคุณเก็บไว้ภายในให้res/font/helvetica.ttfใช้สิ่งต่อไปนี้:
Typeface tf = ResourcesCompat.getFont(this,R.font.helvetica);
txt.setTypeface(tf);
              รับแบบอักษรจากเนื้อหาและตั้งค่าให้กับเด็กทุกคน
public static void overrideFonts(final Context context, final View v) {
    try {
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View child = vg.getChildAt(i);
                overrideFonts(context, child);
         }
        } else if (v instanceof TextView ) {
            ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(),"DroidNaskh.ttf"));// "BKOODB.TTF"));
        }
    } catch (Exception e) {
 }
 } 
              public class FontTextView extends TextView {
    String fonts[] = {"HelveticaNeue.ttf", "HelveticaNeueLight.ttf", "motschcc.ttf", "symbol.ttf"};
    public FontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
    }
    public FontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (!isInEditMode()) {
            init(attrs);
        }
    }
    public FontTextView(Context context) {
        super(context);
        if (!isInEditMode()) {
            init(null);
        }
    }
    private void init(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FontTextView);
            if (a.getString(R.styleable.FontTextView_font_type) != null) {
                String fontName = fonts[Integer.valueOf(a.getString(R.styleable.FontTextView_font_type))];
                if (fontName != null) {
                    Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/" + fontName);
                    setTypeface(myTypeface);
                }
                a.recycle();
            }
        }
    }
}
เพิ่มใน attrs.xml ตัวเลขควรอยู่ในลำดับในคลาสอาเรย์
<declare-styleable name="FontTextView">
<attr name="font_type" format="enum">
    <enum name="HelveticaNeue" value="0"/>
    <enum name="HelveticaNeueLight" value="1"/>
    <enum name="motschcc" value="2"/>
    <enum name="symbol" value="3"/>
</attr>
Android ใช้แบบอักษร Roboto ซึ่งเป็นแบบอักษรที่ดูดีจริง ๆ ด้วยน้ำหนักที่แตกต่างกันหลายประการ (ปกติเบาบางข้น) ที่ดูดีบนหน้าจอที่มีความหนาแน่นสูง
ลิงค์ด้านล่างเพื่อตรวจสอบแบบอักษร roboto:
กลับไปที่คำถามของคุณหากคุณต้องการเปลี่ยนแบบอักษรสำหรับTextView / Button ทั้งหมดในแอปของคุณลองเพิ่มรหัสด้านล่างลงใน styles.xml ของคุณเพื่อใช้แบบอักษรRoboto-light :
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    ......
    <item name="android:buttonStyle">@style/MyButton</item>
    <item name="android:textViewStyle">@style/MyTextView</item>
</style>
<style name="MyButton" parent="@style/Widget.AppCompat.Button">
    <item name="android:textAllCaps">false</item>
    <item name="android:fontFamily">sans-serif-light</item>
</style>
<style name="MyTextView" parent="@style/TextAppearance.AppCompat">
    <item name="android:fontFamily">sans-serif-light</item>
</style>
และอย่าลืมใช้ 'AppTheme' ใน AndroidManifest.xml ของคุณ
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    ......
</application>
              อาจจะง่ายกว่านี้หน่อย:
public class Fonts {
  public static HashSet<String,Typeface> fonts = new HashSet<>();
  public static Typeface get(Context context, String file) {
    if (! fonts.contains(file)) {
      synchronized (this) {
        Typeface typeface = Typeface.createFromAsset(context.getAssets(), name);
        fonts.put(name, typeface);
      }
    }
    return fonts.get(file);
  }
}
// Usage
Typeface myFont = Fonts.get("arial.ttf");
(โปรดทราบว่ารหัสนี้ยังไม่ได้ทดสอบ แต่โดยทั่วไปวิธีนี้ควรใช้งานได้ดี)