Подтвердить что ты не робот

Как создать пользовательский 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" />
4b9b3361

Ответ 1

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" />

Ответ 2

Создайте пользовательский вид для Textview. Шаг 1 - Сделайте запись в файле attrs.xml и дайте возможность выбрать Font as list в пользовательском 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: Создайте класс, расширяющий 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();
    }
}

Вы можете использовать этот пользовательский класс таким образом... используйте свой пакетName.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

Следующий пользовательский класс может помочь вам настроить для установки нужного шрифта на 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);
    }
}