I want to use custom typefaces in my Android application. I use the following method to set custom typeface to all TextView of a Activity
or Fragment
:
public static void setTypeFace(Typeface typeFace, ViewGroup parent){
for (int i = 0; i < parent.getChildCount(); i++) {
View v = parent.getChildAt(i);
if (v instanceof ViewGroup) {
setTypeFace(typeFace, (ViewGroup) v);
} else if (v instanceof TextView) {
TextView tv = (TextView) v;
tv.setPaintFlags(tv.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG);
tv.setTypeface(typeFace);
}
}
}
Activity:
public class MyActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
ViewGroup vg = (ViewGroup)getWindow().getDecorView();
ViewUtil.setTypeFace(tf, vg);
...
}
It works well. But unfortunately font of the ActionBar is also changed. I don't want that..
How can I adapt this method to exclude TextBoxs of the ActionBar?
Thanks!
The solution was to identified the ID name of the two ActionBar TextBox: android:id/action_bar_title
and android:id/action_bar_subtitle
. You can do that with the hierarchyviewer SDK tool (thanks @pskink!).
public static void setTypeFace(Typeface typeFace, ViewGroup parent){
for (int i = 0; i < parent.getChildCount(); i++) {
View v = parent.getChildAt(i);
if (v instanceof ViewGroup) {
setTypeFace(typeFace, (ViewGroup) v);
} else if (v instanceof TextView) {
TextView tv = (TextView) v;
String tvIdName = tv.getResources().getResourceName(tv.getId());
if (!tvIdName.equals("android:id/action_bar_title") && !tvIdName.equals("android:id/action_bar_subtitle")) {
if (DO_SUBPIXEL_RENDERING){
tv.setPaintFlags(tv.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
tv.setTypeface(typeFace);
}
}
}
}
You could create your own TextView by Overriding the TextView like this:
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setType(context);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setType(context);
}
public MyTextView(Context context) {
super(context);
setType(context);
}
private void setType(Context context){
this.setTypeface(Typeface.createFromAsset(context.getAssets(),
"foo.ttf"));
this.setShadowLayer(1.5f, 5, 5, getContext().getResources().getColor(R.color.black_shadow));
}
}
And use it like this:
<com.your.project.package.MyTextView
android:id="@+id/oppinfo_mtv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="Player 1"
/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.