Изменить шрифт для EditText в Android?

есть ли способ изменить шрифт для EditText в Android? Я хочу, чтобы он соответствовал шрифту, который я установил для всех моих textViews.

7 ответов


 editText.setTypeface(Typeface.SERIF); 

как для TextView.

 <TextView
  ...
     android:typeface="serif"
  ... />

Edit: выше находится XML


Solution1:: просто вызовите этот метод, передав родительское представление в качестве аргумента.

private 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 EditText) {
            ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "font.ttf"));
        }
    } catch (Exception e) {
 }
}

Solution2:: вы можете подкласс виджет TextView класса с пользовательских шрифтов и использовать его вместо текстового представления.

public class MyEditView extends EditText{

    public MyEditView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public MyEditView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyEditView(Context context) {
        super(context);
        init();
    }

    private void init() {
        if (!isInEditMode()) {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font.ttf");
            setTypeface(tf);
        }
    }

 }

создать шрифты на активы папку и положить .ttf файл шрифта, затем в функцию onCreate () напишите:

EditText editText =(EditText)findViewById(R.id.insert_yors_edit_text_layout);
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/yours_font.ttf"); 
editText.setTypeface(type);

void setFont(Context context, ViewGroup vg)
        {
          final String FONT_NAME = "lato_bold.ttf";
            for (int i = 0; i < vg.getChildCount(); i++)
                {
                    View v = vg.getChildAt(i);
                    if (v instanceof ViewGroup)
                        setFont(context, (ViewGroup) v);
                    else if (v instanceof TextView)
                        {
                            ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(), FONT_NAME ));
                        }
                    else if (v instanceof EditText)
                        {
                            ((EditText) v).setTypeface(Typeface.createFromAsset(context.getAssets(), FONT_NAME ));
                        }
                    else if (v instanceof Button)
                        {
                            ((Button) v).setTypeface(Typeface.createFromAsset(context.getAssets(), FONT_NAME ));
                        }
                    else if (v instanceof CheckBox)
                        {
                            ((CheckBox) v).setTypeface(Typeface.createFromAsset(context.getAssets(), FONT_NAME ));
                        }
                    else if (v instanceof RadioButton)
                        {
                            ((RadioButton) v).setTypeface(Typeface.createFromAsset(context.getAssets(), FONT_NAME ));
                        }
                }
        }

в вашей деятельности или фрагмент , сделать основной макет

Inflater inflater = (Inflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//For Activity
//Inflater inflater = (Inflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.main_fragment, container, false);
//For Activity
//View v = inflater.inflate(R.layout.signup_fragment, null, false);
if (v instanceof ViewGroup)
    {
      setFont(getActivity(), (ViewGroup) v);
      //For Activity
     //setFont(this, (ViewGroup) v);
    }

вы можете создать шрифт папка в каталоге res в последней версии Android studio 3 .Затем скопировать и мимо него ты шрифт шрифт папка. Теперь просто добавьте fontFamily to полей EditText тег xml.

, как показано ниже.

        <EditText
            android:id="@+id/subject"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/headerShare"
            android:layout_marginBottom="5dp"
            android:layout_marginEnd="16dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:background="@drawable/edittext_bg"
            android:fontFamily="@font/ritaric"
            android:gravity="start"
            android:hint="Subject"
            android:inputType="text"
            android:maxHeight="50dp"
            android:padding="16dp"
            android:textColor="@color/black"
            android:textColorHint="@color/black"
            android:textSize="@dimen/colors_textview_size" />

мы используем:android:fontFamily="@font/ritaric" для применить шрифт на полей EditText.


Первый Способ

используйте этот код в своем классе java

    EditText et_brand=(EditText)findViewById(R.id.et_brand);
    et_brand.setTypeface(Typeface.createFromAsset(getAssets(),"Aspergit Bold.ttf")); 
    //Aspergit Bold.ttf is Font style name of text

Второй Способ

  1. создайте новый класс java, и он, как вы хотите

    public class CustomTextView extends TextView {
    
    public CustomTextView(Context context, AttributeSet attrs, int defStyle) 
    {
    super(context, attrs, defStyle);
    init();
    }
    
    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    init();
    }
    
    public CustomTextView(Context context) {
    super(context);
    init();
    }
    
    private void init() {
       Typeface tf = Typeface.createFromAsset(getContext().getAssets(), 
    "Aspergit Bold.ttf");
    setTypeface(tf);
    }
    }
    
  2. используйте его в своем Xml-файле

                  <YourPackageNAme.CustomEditText
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:background="@null"/>
    

добавьте этот код в свой java-файл Какой тип вы хотите добавить, как обычный, курсив, полужирный, BOLD_ITALIC.

полей EditText.setTypeface (null, шрифт.Курсив);