salmanseifian
salmanseifian

Reputation: 1082

Set Specific Font to my App

For setting a font to android app, I use below function:

public static void persianizer(ViewGroup viewGroup) {

    int childCount = viewGroup.getChildCount();

    for (int i = 0; i < childCount; i++) {
        View child = viewGroup.getChildAt(i);

        if (child instanceof ViewGroup) {
            persianizer((ViewGroup) child);
            continue;
        }

        if (child instanceof TextView) {
            ((TextView) child).setTypeface(RootApp.typeface);
        }

    }

}

It gets the root view of a layout and then set type face for every textview child of that layout. but I think it's not a good solution.

What's the best practice for changing the font of whole application?

Upvotes: 2

Views: 91

Answers (2)

NipunPerfect
NipunPerfect

Reputation: 125

try this

public class CustomTextView extends android.support.v7.widget.AppCompatTextView {

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(),
            "Walkway Black.ttf");
    setTypeface(tf);
}

}

and then use this CustomText view in Your layout Like :

 <app.com.demo.CustomTextView
    android:id="@+id/tv_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="@dimen/_10dp"
    android:inputType=""
    android:text="@string/name"
    android:textColor="@color/colorSkyBlue"
    android:textSize="20sp"
    android:textStyle="bold" />

Upvotes: 0

Hemant Parmar
Hemant Parmar

Reputation: 3976

You can create your own Font TextView class that will extends TextView and send font according to you want, have look:

public class TypefacedTextView extends TextView {

public TypefacedTextView(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.TypefacedButton);
    // String fontName = styledAttrs.getString(R.styleable.TypefacedButton_font);
    styledAttrs.recycle();

    Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/" +getResources().getString(R.string.roboto_light));
    setTypeface(typeface);

}

Save Your fonts file in Assets folder and get by call Typeface.createFromAsset().

Here is the TypeFaceTextview in xml:

     <com.demo.TypefacedTextView 
      android:id="@+id/textview"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:ems="10"       
      </com.demo.TypefacedTextView >

Happy coding!!

Upvotes: 2

Related Questions