Android.mH
Android.mH

Reputation: 71

How to change font to default as defined in Xml?

I have changed fonts of my Textviews using the

Typeface font = Typeface.createFromAsset(this.getAssets(),"fonts/Arial.ttf"); 

In my Xml layout i have many textviews with different fonts, i want to retain this any time programmatically

Tried the following

Typeface.DEFAULT 

and Typeface font =null;

All the textviews are set to same font not the ones in Xml

How to retain the font without having to restart my app?

Upvotes: 1

Views: 323

Answers (2)

Amit Gupta
Amit Gupta

Reputation: 8939

Step 1)create a class name as CustomTextView and copy paste this code but make sure that the custom font should be Project Assets folder. So you can replace font name.

package YOUR_PACKAGE;

public class CustomTextView extends TextView{

    public CustomButton(Context context) {
        super( context );
        setFont();

    }

    public CustomTextView (Context context, AttributeSet attrs) {
        super( context, attrs );
        setFont();
    }

    public CustomTextView (Context context, AttributeSet attrs, int defStyle) {
        super( context, attrs, defStyle );
        setFont();
    }

    private void setFont() {
        Typeface normal = Typeface.createFromAsset(getContext().getAssets(),"fonts/Arial.ttf");
        setTypeface( normal, Typeface.NORMAL );

    }
}

Step-2)

Use This custom TextView in your layout

<LinearLayout
        android:id="@+id/signing_details"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:orientation="vertical"
        android:weightSum="100" >

<YOUR_PACKAGE.CustomTextView
                android:id="@+id/textview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                 android:text="@string/app_name"
                 android:textSize="16sp" />
</ LinearLayout>

You can also use this CustomTextView dynamically

 CustomTextView textView = new CustomTextView (this);
 textView.setText(res.getString(R.string.app_name));
 textView.setTextColor(Color.parseColor("#000000"));
 textView.setTextSize(16);

Hope this help you.

Upvotes: 0

Diego Palomar
Diego Palomar

Reputation: 7061

A possible solution could be using static instances of TypeFace class. Some time ago I proposed a solution to this problem in this thread: Access a typeface once from asset and use it as a reference. I hope you find it useful.

Upvotes: 1

Related Questions