2011-07-19 27 views
23

Tôi đang cố gắng thực hiện thay đổi phông chữ trong ứng dụng và tạo tệp kiểu để làm như vậy. Trong tập tin này (bên dưới), tôi chỉ muốn thay đổi giá trị kiểu chữ của phong cách TextAppearance của Android.Truy cập phông chữ trong thư mục tài sản từ tệp XML trong Android

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <style name="NightRiderFont" parent="@android:style/TextAppearance"> 
     <item name="android:typeface"> /***help need here***/ </item> 
    </style> 
</resources> 

Tuy nhiên phông chữ nằm trong "nội dung/phông chữ /". Làm thế nào tôi có thể truy cập phông chữ này, vì vậy tôi có thể sử dụng phong cách đó làm chủ đề để loại bỏ việc thay đổi tất cả TextView bằng tay theo chương trình.

Tóm tắt: Làm cách nào để truy cập 'tệp từ thư mục nội dung' trong XML?

Trả lời

67

Trong nghiên cứu của tôi, không có cách nào để thêm phông chữ bên ngoài vào tệp xml. Chỉ có 3 phông chữ mặc định có sẵn trong xml

Nhưng bạn có thể sử dụng trong java bằng cách sử dụng mã này.

Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/verdana.ttf"); 
textfield.setTypeface(tf,Typeface.BOLD); 

Cập nhật:

Bây giờ tôi tìm thấy một cách để làm điều này bằng cách tạo một lớp tùy chỉnh mở rộng TextView và sử dụng trong file xml.

public class TextViewWithFont extends TextView { 
    private int defaultDimension = 0; 
    private int TYPE_BOLD = 1; 
    private int TYPE_ITALIC = 2; 
    private int FONT_ARIAL = 1; 
    private int FONT_OPEN_SANS = 2; 
    private int fontType; 
    private int fontName; 

    public TextViewWithFont(Context context) { 
     super(context); 
     init(null, 0); 
    } 
    public TextViewWithFont(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(attrs, 0); 
    } 
    public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     init(attrs, defStyle); 
    } 
    private void init(AttributeSet attrs, int defStyle) { 
     // Load attributes 
     final TypedArray a = getContext().obtainStyledAttributes(
       attrs, R.styleable.font, defStyle, 0); 
     fontName = a.getInt(R.styleable.font_name, defaultDimension); 
     fontType = a.getInt(R.styleable.font_type, defaultDimension); 
     a.recycle(); 
     MyApplication application = (MyApplication) getContext().getApplicationContext(); 
     if (fontName == FONT_ARIAL) { 
      setFontType(application .getArialFont()); 
     } else if (fontName == FONT_OPEN_SANS) { 
      setFontType(application .getOpenSans()); 
     } 
    } 
    private void setFontType(Typeface font) { 
     if (fontType == TYPE_BOLD) { 
      setTypeface(font, Typeface.BOLD); 
     } else if (fontType == TYPE_ITALIC) { 
      setTypeface(font, Typeface.ITALIC); 
     } else { 
      setTypeface(font); 
     } 
    } 
} 

và trong xml

<com.example.customwidgets.TextViewWithFont 
     font:name="Arial" 
     font:type="bold" 
     android:layout_width="wrap_content" 
     android:text="Hello world " 
     android:padding="5dp" 
     android:layout_height="wrap_content"/> 

không quên để thêm lược đồ trong thư mục gốc của xml của bạn

xmlns:font="http://schemas.android.com/apk/res-auto" 

Và tạo ra một tập tin attrs.xml bên values thư mục, mà đang nắm giữ attribues tùy chỉnh của chúng tôi :

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="font"> 
     <attr name="type"> 
     <enum name="bold" value="1"/> 
      <enum name="italic" value="2"/> 
     </attr> 
     <attr name="name"> 
      <enum name="Arial" value="1"/> 
      <enum name="OpenSans" value="2"/> 
     </attr> 
    </declare-styleable> 
</resources> 

Cập nhật:

Tìm thấy một số vấn đề hiệu suất khi xem phong tục này được sử dụng trong listview, đó là bởi vì các đối tượng chữ đang tạo ra mỗi khi xem được tải. Giải pháp tôi thấy là để khởi tạo phông chữ trong ứng dụng Class và tham khảo đối tượng chữ bằng cách

MyApplication application = (MyApplication) getContext().getApplicationContext(); 

lớp Application sẽ trông như thế này

public class MyApplication extends Application { 

    private Typeface arialFont, openSans; 

    public void onCreate() { 
     super.onCreate(); 

     arialFont = Typeface.createFromAsset(getAssets(), QRUtils.FONT_ARIAL); 
     openSans = Typeface.createFromAsset(getAssets(), QRUtils.FONT_OPEN_SANS); 
    } 

    public Typeface getArialFont() { 
     return arialFont; 
    } 

    public Typeface getOpenSans() { 
     return openSans; 
    } 
} 
+0

Vâng, thật khó để thay đổi tất cả phông chữ đơn, nhưng có vẻ như không có gì khác để làm. – erkangur

+0

Ya tôi biết. Tôi cũng có tình huống tương tự trước đây. –

+0

Cảm ơn, điều này đã làm việc cho tôi. Nhưng có ai đi qua tài liệu chính thức là tại sao bạn không thể đặt một kiểu chữ tùy chỉnh trong một tệp XML? – toobsco42

2

Soorya là đúng, nhưng nếu bạn cần phải đặt cùng một phông chữ trên nhiều textViews, tôi khuyên bạn nên đặt mã đó bên trong một phương thức tĩnh trả về kiểu chữ mong muốn. Nó sẽ làm giảm các dòng trong mã của bạn. Hoặc thậm chí tốt hơn là tạo một lớp mở rộng ứng dụng và tạo phương thức GET trả về kiểu chữ. Phương thức đó sẽ có thể truy cập được từ bất kỳ Hoạt động nào bên trong ứng dụng của bạn (mà không cần sử dụng các biến tĩnh hoặc các phương thức tĩnh).

+0

vâng .. bạn đang ở ngay –

0

sử dụng hy vọng đầy đủ cho bạn: -

TextView text = (TextView) findViewById(R.id.custom_font); 
Typeface font = Typeface.createFromAsset(getAssets(), "yourfont.ttf"); 
text.setTypeface(font); 
6

Chỉnh sửa 2:

Cuối cùng phông chữ được hỗ trợ bởi xml (cũng tương thích ngược qua thư viện hỗ trợ): https://developer.android.com/preview/features/fonts-in-xml.html


Chỉnh sửa:

Tôi hiện đang sử dụng thư viện Calligraphy. Đây là cách dễ nhất cho phông chữ tùy chỉnh.

bạn có thể làm gì:

  • Tuỳ chỉnh phông chữ trong một phông chữ Tuỳ chỉnh TextView
  • trong TextAppearance
  • Tuỳ chỉnh phông chữ trong Styles
  • Tuỳ chỉnh phông chữ trong Chủ đề
  • FontSpannable để chỉ áp dụng phông chữ một phần của văn bản

Tôi tìm thấy một cách khác để thực hiện việc này.

Bạn cần phải làm của riêng bạn TextView sử dụng này tutorial

Nó không phải là khó khăn và sau đó bạn chỉ có thể sử dụng TextView với phông chữ của riêng bạn.

Tôi không biết liệu có ai vẫn xem điều này không, nhưng tôi nghĩ điều đó có thể hữu ích.

+0

Cảm ơn Kevin, nó đá! –

4

Sử dụng chức năng này nếu bạn đang sử dụng một phông chữ.

public static void applyFont(final Context context, final View root, final String fontName) { 
     try { 
      if (root instanceof ViewGroup) { 
       ViewGroup viewGroup = (ViewGroup) root; 
       for (int i = 0; i < viewGroup.getChildCount(); i++) 
        applyFont(context, viewGroup.getChildAt(i), fontName); 
      } else if (root instanceof TextView) 
       ((TextView) root).setTypeface(Typeface.createFromAsset(context.getAssets(), fontName)); 
     } catch (Exception e) { 
      Log.e("ProjectName", String.format("Error occured when trying to apply %s font for %s view", fontName, root)); 
      e.printStackTrace(); 
     } 
    } 
+0

Tốt .................... cảm ơn –

+2

hiệu suất của nó như thế nào? – atasoyh

+0

nơi tôi nên gọi chức năng của bạn? –

-2

Bạn có thể truy cập tệp phông chữ của mình từ thư mục nội dung tới tệp xml.

android: fontFamily = "fonts/roboto_regular.ttf"

phông chữ là thư mục phụ trong thư mục nội dung.

1

thay đổi suối là rất chức năng cơ bản trong Android mà chủ yếu là cần thiết để mỗi application.so mọi người muốn thay đổi một lần duy nhất trong ứng dụng làm giảm thời gian phát triển của chúng tôi vì vậy tôi sẽ đề nghị bạn để xem liên kết này FountChanger.class.

0

Bạn có thể sử dụng thư viện này: https://github.com/chrisjenx/Calligraphy

Bạn chỉ cần thêm các font bạn muốn sử dụng trên bố trí của bạn. Như thế này:

<TextView 
fontPath="fonts/verdana.ttf" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content"/> 
0

Bạn vừa thực hiện cuộc gọi Công Và kèm theo Phương pháp như thế này

public class TextViewFontType { 

public Typeface typeface; 

public void fontTextView(final TextView textView, final String fonttype) { 
    typeface = Typeface.createFromAsset(textView.getContext().getAssets(), fonttype); 
    textView.setTypeface(typeface); 
} 

có bạn sử dụng bất kỳ nơi phương pháp TextView thiết lập font-family.

public class FontList { 

    public static final String gothicbNormal="fonts/gothicb.ttf"; 
    public static final String gothicbBold="fonts/gothicb.ttf"; 
} 

làm cho FontList calss sau khi bạn chỉ cần gọi phương thức bất kỳ nơi nào có thông số hai.

0

tôi lấy câu trả lời droid đứa trẻ và làm cho nó làm việc với bất kỳ font chữ, chỉ bằng cách gõ tên tập tin phông chữ trực tiếp vào XML:

Layout.xml

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:custom="http://schemas.android.com/apk/res-auto" > 

    <!-- where font file is at "assets/fonts/arial.ttf" --> 
    <com.odbol.widgets.TextViewWithFont 
     ... 
     custom:fontFilePath="fonts/arial.ttf" /> 

</RelativeLayout> 

Fonts.java

public class Fonts { 

    // use Weak so fonts are freed from memory when you stop using them 
    private final static Map<String, Typeface> fonts = new WeakHashMap<>(5); 

    /*** 
    * Returns a font at the given path within the assets directory. 
    * 
    * Caches fonts to save resources. 
    * 
    * @param context 
    * @param fontPath Path to a font file relative to the assets directory, e.g. "fonts/Arial.ttf" 
    * @return 
    */ 
    public synchronized static Typeface getFont(Context context, String fontPath) { 
     Typeface font = fonts.get(fontPath); 

     if (font == null) { 
      font = Typeface.createFromAsset(context.getAssets(), fontPath); 
      fonts.put(fontPath, font); 
     } 

     return font; 
    } 
} 

giá trị/attrs.xml

<resources> 

    <declare-styleable name="TextViewWithFont"> 
     <!-- a path to a font, relative to the assets directory --> 
     <attr name="fontFilePath" format="string" /> 

     <attr name="type"> 
      <enum name="bold" value="1"/> 
      <enum name="italic" value="2"/> 
     </attr> 
    </declare-styleable> 
</resources> 

TextViewWithFont.java

public class TextViewWithFont extends TextView { 
    private int defaultDimension = 0; 
    private int TYPE_BOLD = 1; 
    private int TYPE_ITALIC = 2; 
    private int fontType; 
    private int fontName; 

    public TextViewWithFont(Context context) { 
     super(context); 
     init(null, 0); 
    } 
    public TextViewWithFont(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(attrs, 0); 
    } 
    public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     init(attrs, defStyle); 
    } 
    private void init(AttributeSet attrs, int defStyle) { 
     // Load attributes 
     final TypedArray a = getContext().obtainStyledAttributes(
       attrs, R.styleable.TextViewWithFont, defStyle, 0); 
     String fontPath = a.getString(R.styleable.TextViewWithFont_fontFilePath); 
     fontType = a.getInt(R.styleable.TextViewWithFont_type, defaultDimension); 
     a.recycle(); 

     if (fontPath != null) { 
      setFontType(Fonts.getFont(getContext(), fontPath)); 
     } 
    } 
    private void setFontType(Typeface font) { 
     if (fontType == TYPE_BOLD) { 
      setTypeface(font, Typeface.BOLD); 
     } else if (fontType == TYPE_ITALIC) { 
      setTypeface(font, Typeface.ITALIC); 
     } else { 
      setTypeface(font); 
     } 
    } 
} 
0

1.Fisrt chúng ta có thể bổ sung tài sản thư mục> ở chỗ styles.ttfs phông chữ của bạn trong ứng dụng của bạn sau đó
2.write mã truy cập cho các phông chữ trong các chuỗi như:

<string name="fontregular">OpenSans-Light.ttf</string> 
<string name="fontmedium">OpenSans-Regular.ttf</string> 

3.Truy cập một số bố cục tệp văn bản xml dưới dạng văn bản dưới đây:

 <EditText 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:fontFamily="@string/fontregular" 
     android:textColor="@color/normalfont" 
     android:textSize="@dimen/textregular"/> 

kích thước 4.Add cho cỡ chữ:

<dimen name="textregular">14sp</dimen> 
<dimen name="textheader">16sp</dimen> 
<dimen name="smalltext">12sp</dimen> 
<dimen name="littletext">10sp</dimen> 
<dimen name="hightfont">18sp</dimen> 

5.Add font color màu sắc:

<color name="normalfont">#666</color> 
<color name="headerfont">#333</color> 
<color name="aquablue">#4da8e3</color> 
<color name="orange">#e96125</color> 

6.Then áp dụng thay đổi nó rất dễ dàng quá trình để thay đổi ứng dụng lỗ . Chúc mừng mã hóa giữ nụ cười ..

Các vấn đề liên quan