Android: How to custom-declare XML namespace in styles.xml?
1) you need to define an attribute for your fonts in attr.xml file in res folder:
<attr name="myfonts" format="string"></attr>
2) you need to define custom style for your TextView and here we use our defined attribute(myfonts):
<declare-styleable name="MyCustomStyle"> <attr name="myfonts" /></declare-styleable>
3)
<style name="CoolTextView"> <item name="myfonts">ReallyCoolFont.ttf</item></style>
summary of what you have so far:
<?xml version="1.0" encoding="utf-8"?><resources> <attr name="myfonts" format="string"> </attr> <declare-styleable name="MyCustomStyle"> <attr name="myfonts" /> </declare-styleable> <style name="CoolTextView"> <item name="myfonts">ReallyCoolFont.ttf</item> </style></resources>
4)Now your layout would be:
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" > <com.example.MyCustomTextView android:id="@+id/result" style="@style/CoolTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="HELLO WORLD!" android:textSize="24dp" android:gravity="center" > </com.example.MyCustomTextView></RelativeLayout>
5)and your MyCustomTextView is:
public class MyCustomTextView extends TextView { private static final String TAG = "TextView"; public MyCustomTextView(Context context) { super(context); } public MyCustomTextView(Context context, AttributeSet attrs) { super(context, attrs); settingFont(context, attrs); } public MyCustomTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); settingFont(context, attrs); } private void settingFont(Context ctx, AttributeSet attrs) { TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.MyCustomStyle); String customFont = a.getString(R.styleable.MyCustomStyle_myfonts); Typeface tf = null; try { tf = Typeface.createFromAsset(ctx.getAssets(), customFont); } catch (Exception e) { Log.e(TAG,e.getMessage()); a.recycle(); return; } setTypeface(tf); a.recycle(); }}
I assumed you put the font in asset not in asset/fonts directory.
also I highly recommend read this.
You don't need to add any prefix to reference your custom attributes in the style resource files. Doing it like this will work just fine:
<style name="CoolTextView"> <item name="customFont">ReallyCoolFont.ttf</item></style>
The answer is to NOT specify the namespace in the style.
<?xml version="1.0" encoding="utf-8" ?><resources xmlns:custom="http://schemas.android.com/apk/res/com.custom.project"> <style name="CustomStyle"> <item name="android:layout_width">wrap_content</item> <item name="android:layout_height">wrap_content</item> <item name="customAttr">value</item> <!-- tee hee --> </style></resources>