October 19th, 2012, 12:28 PM
|
#4 (permalink)
|
|
Junior Member
Join Date: Feb 2012
Gender: Male
Posts: 29
Device(s):
Carrier: Not Provided
Thanks: 1
Thanked 10 Times in 8 Posts
|
As far as I've seen you can only set the built in fonts as part of a style.
You can create a custom class the extends textview. Here is an example I found:
Quote:
There is a fairly easy way to do this via XML. You just need to create your own widget that extends TextView.
First, create a file in res/values/attrs.xml with the following content:
Code:
<resources>
<declare-styleable name="TypefacedTextView">
<attr name="typeface" format="string" />
</declare-styleable>
</resources>
After that, create your custom widget:
Code:
package your.package.widget;
public class TypefacedTextView extends TextView {
public TypefacedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
//Typeface.createFromAsset doesn't work in the layout editor. Skipping...
if (isInEditMode()) {
return;
}
TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.TypefacedTextView);
String fontName = styledAttrs.getString(R.styleable.TypefacedTextView_typeface);
styledAttrs.recycle();
if (fontName != null) {
Typeface typeface = Typeface.createFromAsset(context.getAssets(), fontName);
setTypeface(typeface);
}
}
}
As you can see, the code above will read a font inside the assets/ folder. For this example, I am assuming that there is a file called "custom.ttf" in the assets folder. At last, use the widget in the XMLs:
Code:
<your.package.widget.TypefacedTextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:your_namespace="http://schemas.android.com/apk/res/your.package"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Custom fonts in XML are easy"
android:textColor="#FFF"
android:textSize="14dip"
your_namespace:typeface="custom.ttf" />
Note: you won't be able to see your custom font in Eclipse's layout editor. This is why I put the isInEditMode() check. But if you run your app, the custom font will work like a charm.
|
|
|
|