Monday, 23 April 2012

Set custom typeface to all the child view of the layout.

Hello guys, Today I am updating my blog for set the custom typeface from the activity.

If we have to apply the typeface to our application then we need to mapping all the widgets from the xml to Activity by calling the method findViewById. So it will be boring if we will have many Textview, Buttons and EditText in our layout.

For this I have created one method by which you can set typeface to all the widgets in your layout.

Here is my code to create a typeface from ttf file which is in the assets folder


public static Typeface getTypeface(Context c) {
        Typeface typeface = Typeface.createFromAsset(c.getAssets(), "DroidHindi.ttf");
        return typeface;
}

I have one another method which is for return the root view of the view-hierarchy.


public static ViewGroup getParentView(View v) {
        ViewGroup vg = null;
        if(v != null) {
        vg = (ViewGroup) v.getRootView();
        }
        return vg;
}

Now I have one method which is responsible for set the typeface to all the child view of the root layout.



public static void applyTypeface(ViewGroup v, Typeface f) {
if(v != null) {
int vgCount = v.getChildCount();
for(int i=0;i<vgCount;i++) {
      if(v.getChildAt(i) == null) continue;
if(v.getChildAt(i) instanceof ViewGroup) {
applyTypeface((ViewGroup)v.getChildAt(i), f);
}else {
View view = v.getChildAt(i);
if(view instanceof TextView) {
((TextView)(view)).setTypeface(f);
}else if(view instanceof EditText) {
((EditText)(view)).setTypeface(f);
}else if(view instanceof Button) {
((Button)(view)).setTypeface(f);
}
}
}
}
}

You can see in this method there are two arguments one is view-group and another is typeface.
So this method will basically get all the child of the view-group and check weather it is view-group or nor if it is again a view-group then it will again call this same method again or if child is the view then it will compare the instance of the view with TextView, EditText or Button. If view is instance of this three Views then it will set the typeface to these views.

Now from the activity if you wanna use this method you have to write a below code.


UDF.applyTypeface(UDF.getParentView(btnBack), UDF.getTypeface(context));

Note:: 

  1. UDF is the class in which these all methods are resides. 
  2. getParentView() method takes argument view, You can pass any view of your activity to get the root view of the layout of activity






1 comment:

  1. Super! I had the same idea, and found it implemented here. Thanks! ;)

    ReplyDelete