2012-02-28 4 views
23

Я пытаюсь создать пользовательский текстовый вид, который имеет шрифт, заданный с заданного пути. Просьба предоставить мне какой-либо пример, и как я могу сделать это с меньшим количеством кода:Как создать пользовательский TextView?

<TextView 
    android:id="@+id/textView2" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/accountInfoText" 
    android:textColor="#727272" 
    android:textSize="18dp" /> 
+1

см [это] (http://developer.android.com/guide/topics/ui/themes.html) – Ghost

ответ

83
import android.content.Context; 
import android.graphics.Canvas; 
import android.graphics.Typeface; 
import android.util.AttributeSet; 
import android.widget.TextView; 

public class FontTextView extends TextView { 


   public FontTextView(Context context) { 
     super(context); 
     Typeface face=Typeface.createFromAsset(context.getAssets(), "Helvetica_Neue.ttf"); 
     this.setTypeface(face); 
   } 

   public FontTextView(Context context, AttributeSet attrs) { 
       super(context, attrs); 
    Typeface face=Typeface.createFromAsset(context.getAssets(), "Helvetica_Neue.ttf"); 
 this.setTypeface(face); 
   } 

   public FontTextView(Context context, AttributeSet attrs, int defStyle) { 
       super(context, attrs, defStyle); 
    Typeface face=Typeface.createFromAsset(context.getAssets(), "Helvetica_Neue.ttf"); 
 this.setTypeface(face); 
   } 

   protected void onDraw (Canvas canvas) { 
       super.onDraw(canvas); 
        
      
   } 

} 

и в XML:

<com.util.FontTextView 
                   android:id="@+id/textView2" 
                   android:layout_width="wrap_content" 
                   android:layout_height="wrap_content" 
                   android:text="@string/accountInfoText" 
                   android:textColor="#727272" 
                   android:textSize="18dp" /> 
+28

Я рекомендую использовать синглтон для нанесения шрифта, чтобы избежать каждый раз создавая шрифт из активов. – JackMahoney

+0

@JackMahoney +1 для вашего очень полезного комментария. Теперь мое приложение очень быстро! –

+0

@JackMahoney у вас есть пример преобразования пользовательского представления в singleton, чтобы показать его? Было бы полезно. – kabuto178

-1

Ниже пользовательский класс может помочь вам настроить и для настройки нужного шрифта на TextView, поэтому вам нужно поместить некоторый .ttf-файл в активы и указать этот путь на пользовательском TextView.

public class TextViewBoldFont extends TextView { 
    public TextViewBoldFont(Context context, AttributeSet attrs) { 
     super(context, attrs); 

     String fontPath = "GOTHICB.TTF"; 
     Typeface fontsStyle = Typeface.createFromAsset(context.getAssets(), fontPath); 
     this.setTypeface(fontsStyle,Typeface.BOLD); 
    } 

    public TextViewBoldFont(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 

     String fontPath = "GOTHICB.TTF"; 
     Typeface fontsStyle = Typeface.createFromAsset(context.getAssets(), fontPath); 
     this.setTypeface(fontsStyle,Typeface.BOLD); 
    } 

    public TextViewBoldFont(Context context) { 
     super(context); 

     String fontPath = "GOTHICB.TTF"; 
     Typeface fontsStyle = Typeface.createFromAsset(context.getAssets(), fontPath); 
     this.setTypeface(fontsStyle,Typeface.BOLD); 
    } 
} 
+2

Привет, добро пожаловать в SO. Пожалуйста, не отправляйте код в качестве ответа, объясните свой ход мысли, чтобы пользователи могли понять, что вы делаете. Благодарю. – Cthulhu

18

Создать собственный вид для Textview. Шаг 1 - Сделайте запись в файле attrs.xml и дайте возможность выбрать Шрифт как список в пользовательском TextView.

<declare-styleable name="CustomFontTextView"> 
    <attr name="fontName"/> 
</declare-styleable> 

Шаг 2: Создайте запись перечислимую со списком шрифтов и присвоить уникальные значения

<attr name="fontName" format="enum"> 
    <enum name="Roboto_Bold" value="1" /> 
    <enum name="Roboto_Italic" value="2" /> 
    <enum name="Roboto_Light" value="3" /> 
    <enum name="Roboto_Medium" value="4" /> 
    <enum name="Roboto_Regular" value="5" /> 
    <enum name="Roboto_Thin" value="6" /> 
</attr> 

Шаг 3: Сделайте записи всех шрифтов в strings.xml

<string name="Roboto_Bold">Roboto-Bold</string> 
<string name="Roboto_Medium">Roboto-Medium</string> 
<string name="Roboto_Light">Roboto-Light</string> 
<string name="Roboto_Regular">Roboto-Regular</string> 
<string name="Roboto_Thin">Roboto-Thin</string> 
<string name="Roboto_Italic">Roboto-Italic</string> 

Шаг 4: создать и скопируйте все необходимые шрифты, которые вы хотите поместить в папку шрифтов

Шаг 5: Создайте клаву ss extend TextView

import android.content.Context; 
import android.content.res.TypedArray; 
import android.graphics.Typeface; 
import android.util.AttributeSet; 
import android.widget.TextView; 

/** 
* Created by ANKIT 
*/ 
public class CustomFontTextView extends TextView { 

    String customFont; 

    public CustomFontTextView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     style(context, attrs); 
    } 

    public CustomFontTextView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     style(context, attrs); 

    } 

    private void style(Context context, AttributeSet attrs) { 

     TypedArray a = context.obtainStyledAttributes(attrs, 
       R.styleable.CustomFontTextView); 
     int cf = a.getInteger(R.styleable.CustomFontTextView_fontName, 0); 
     int fontName = 0; 
     switch (cf) 
     { 
      case 1: 
       fontName = R.string.Roboto_Bold; 
       break; 
      case 2: 
       fontName = R.string.Roboto_Italic; 
       break; 
      case 3: 
       fontName = R.string.Roboto_Light; 
       break; 
      case 4: 
       fontName = R.string.Roboto_Medium; 
       break; 
      case 5: 
       fontName = R.string.Roboto_Regular; 
       break; 
      case 6: 
       fontName = R.string.Roboto_Thin; 
       break; 
      default: 
       fontName = R.string.Roboto_Regular; 
       break; 
     } 

     customFont = getResources().getString(fontName); 

     Typeface tf = Typeface.createFromAsset(context.getAssets(), 
       "font/" + customFont + ".ttf"); 
     setTypeface(tf); 
     a.recycle(); 
    } 
} 

Вы можете использовать этот пользовательский класс таким образом. .. использовать ваш packageName.ClassName

<ankit.com.customui.CustomFontTextView 
    android:layout_width="match_parent" 
    android:text="Hello World Ankit" 
    android:textSize="16sp" 
    app:fontName="Roboto_Medium" 
    android:layout_height="wrap_content"/> 
+3

намного лучше, чем принятый ответ. –

Смежные вопросы