Changing minSdkVersion from 15 to 16 - android

When I changed my minSdkVersion then I am getting this error:
android.view.InflateException: Binary XML file line #43: Error inflating class TextView
Eariler it was working fine before I have made the changes.
Here is my style :
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
<style name="AppTheme.Dark" parent="Theme.AppCompat.NoActionBar">
<item name="colorPrimary">#color/primary</item>
<item name="colorPrimaryDark">#color/primary_dark</item>
<item name="colorAccent">#color/white</item>
<item name="colorControlNormal">#color/greyDark</item>
<item name="colorControlActivated">#color/off_white</item>
<item name="android:windowBackground">#color/pink</item>
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>
<item name="android:windowContentTransitions" tools:targetApi="lollipop">true</item>
<item name="android:windowAllowEnterTransitionOverlap" tools:targetApi="lollipop">true</item>
<item name="android:windowAllowReturnTransitionOverlap" tools:targetApi="lollipop">true</item>
<item name="android:windowSharedElementEnterTransition" tools:targetApi="lollipop">#android:transition/move</item>
<item name="android:windowSharedElementExitTransition" tools:targetApi="lollipop">#android:transition/move</item>
</style>
<style name="AlertDialogCustom" parent="#android:style/Theme.Dialog">
<item name="android:textColor">#color/pink</item>
<item name="android:typeface">normal</item>
<item name="android:height">5dp</item>
<item name="android:textSize">20sp</item>
<item name="android:textStyle">bold</item>
<item name="android:background">#color/white</item>
</style>
I guess there is something wrong with the parent property of a style.

If you are changing your version then also change the support library.You have to change the support lib like for e.g.for api 23 you have to chnage the appcompact library version to 23.
Hope this help.:)

You should try changing
<style name="AlertDialogCustom" parent="#android:style/Theme.Dialog">
to
<style name="AlertDialogCustom" parent="Theme.AppCompat.Dialog">

This is the issue with your font family which you are using in style. May be sans-serif-light font is not available in your assests>>fonts folder. So check with this how to use custom fonts in android.
Here are the steps to follow:
Android Studio:
Step1: Adding font family files to app
A) Go to the (project folder)
B) Then app>src>main
C) Create folder 'assets>fonts' into the main folder.
D) Put your 'abc.ttf' or 'abc.otf' font file into the fonts folder.
Step 2:
Now Create attrs.xml under res folder if it's not exists and add declare-styleable
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Font">
<attr name="typeface">
<enum name="FuturaLT" value="0" />
<enum name="FuturaLT_Heavy" value="1" />
<enum name="FuturaLT_Light" value="2" />
</attr>
</declare-styleable>
</resources>
//Here FuturaLT/FuturaLT_Heavy/FuturaLT_Light are file names
Note: – enum name should be font type name with underscore(_) uses, it will be easy for you to understand font family usage in your native code. No special character or other letter, otherwise you will got error in gen folder for same attribute id.
Step 3: Create your custom view(Button, TextView, EditText) class:-
package com.myapp.views;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.TextView;
import com.myapp.R;
public class CustomTextView extends TextView {
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
try {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Font);
int font = a.getInt(R.styleable.Font_typeface, 0);
a.recycle();
String str;
switch (font) {
case 1:
str = "fonts/FuturaLT.otf";
break;
case 2:
str = "fonts/FuturaLT_Heavy.otf";
break;
case 3:
str = "fonts/FuturaLT_Light.otf";
break;
default:
str = "fonts/FuturaLT.otf";
break;
}
setTypeface(FontManager.getInstance(getContext()).loadFont(str));
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressWarnings("unused")
private void internalInit(Context context, AttributeSet attrs) {
}
}
Step 4: Add FontManager.java support class
package com.myapp.views;
import android.content.Context;
import android.graphics.Typeface;
import java.util.HashMap;
import java.util.Map;
public class FontManager {
private Map<String, Typeface> fontCache = new HashMap<String, Typeface>();
private static FontManager instance = null;
private Context mContext;
private FontManager(Context mContext2) {
mContext = mContext2;
}
public synchronized static FontManager getInstance(Context mContext) {
if (instance == null) {
instance = new FontManager(mContext);
}
return instance;
}
public Typeface loadFont(String font) {
if (false == fontCache.containsKey(font)) {
fontCache.put(font, Typeface.createFromAsset(mContext.getAssets(), font));
}
return fontCache.get(font);
}
}
Step 5: Usage in XML layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical">
<com.myapp.views.CustomTextView
android:id="#+id/tv_time_slot"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
app:typeface="FuturaLT" />
</LinearLayout>
You can also use in java code directly:
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/FuturaLT.ttf");
tvText.setTypeface(tf);
Note:- If you don't use here FontManager to apply typeface and directly use
then you are not able to see your views in graphics preview.

Related

Having a issue on applying custom font in android app

I want to set a custom font in my app and done that by
Is it possible to set a custom font for entire of application?
and i have done it but the problem is when i apply AppTheme_1 it changes font for android version greater than or equal to lollipop and when i apply AppTheme_2
then it changes fonts for only android version less than lollipop. But I want to change the font for all android versions.
<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
</style>
<style name="AppTheme_1" parent="AppBaseTheme">
<!-- Customize your theme here. -->
<item name="android:textAppearance">#style/CustomTextAppearance</item>
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:windowContentOverlay">#null</item>
</style>
<style name="CustomTextAppearance">
<item name="android:typeface">serif</item>
</style>
</style>
<style name="AppTheme_2" parent="AppBaseTheme">
<!-- Customize your theme here. -->
<item name="android:typeface">serif</item>
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:windowContentOverlay">#null</item>
</style>
We can achieve to set a single font to entire application using Calligraphy lib
Here is the library link: Calligraphy
Now add compile 'uk.co.chrisjenx:calligraphy:2.3.0' in your build.gradle
Now create an application class like follows:
public class MyApplication extends Application {
private static MyApplication sInstance;
public static MyApplication getInstance() {
return sInstance;
}
#Override
public void onCreate() {
super.onCreate();
sInstance = this;
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Roboto-Regular.ttf")
.setFontAttrId(R.attr.fontPath)
.build());
}}
Now you need to call this application class in manifest file like follows in application tag
android:name=".MyApplication"
By doing this entire app have set one font. You can go through the library for better understanding.
Try this
MyApplication.java (This is Application class)
//Typeface
public static Typeface poppinsSemiBold;
public static Typeface helveticaNeueMedium;
public static Typeface poppinsRegular;
/**
* Preload typefaces.
*/
private void preloadTypefaces() {
poppinsSemiBold = Typefaces.get(getApplicationContext(), Typefaces.FONT_POPPINS_SEMI_BOLD);
helveticaNeueMedium = Typefaces.get(getApplicationContext(), Typefaces.FONT_HELVETICANEUE_MEDIUM);
poppinsRegular = Typefaces.get(getApplicationContext(), Typefaces.FONT_POPPINS_REGULAR);
}
call this preloadTypefaces() in onCreate() of same class MyApplication.java
Typefaces.java
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import java.util.Hashtable;
public class Typefaces {
private static final String TAG = Typefaces.class.getSimpleName();
public static final String FONT_POPPINS_SEMI_BOLD = "fonts/Poppins_SemiBold.ttf";
public static final String FONT_HELVETICANEUE_MEDIUM = "fonts/HelveticaNeue_Medium.otf";
public static final String FONT_POPPINS_REGULAR = "fonts/Poppins_Regular.ttf";
private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();
public static Typeface get(Context c, String assetPath) {
synchronized (cache) {
if (!cache.containsKey(assetPath)) {
try {
Typeface t = Typeface.createFromAsset(c.getAssets(), assetPath);
cache.put(assetPath, t);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface '" + assetPath
+ "' because " + e.getMessage());
return null;
}
}
return cache.get(assetPath);
}
}
}
Make sure your .ttf or .otf file is in assets/fonts/HelveticaNeue_Medium.otf added like that
res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomFontTextView">
<attr name="fontStyle" format="enum">
<enum name="poppinsSemiBold" value="1" />
<enum name="helveticaNeueMedium" value="2" />
<enum name="poppinsRegular" value="3" />
</attr>
</declare-styleable>
<declare-styleable name="TextViewPlus">
<attr name="customFont" format="string" />
</declare-styleable>
</resources>
Custom Font class
TextViewPlus.java
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
import com.offerbuk.R;
import com.offerbuk.app.MyApplication;
public class TextViewPlus extends TextView {
private static final String TAG = "TextViewPlus";
private int fontStyle;
private TypedArray a = null;
public TextViewPlus(Context context) {
super(context);
init(null, 0);
}
public TextViewPlus(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public TextViewPlus(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle) {
try {
this.a = getContext().obtainStyledAttributes(attrs, R.styleable.CustomFontTextView, defStyle, 0);
this.fontStyle = a.getInteger(R.styleable.CustomFontTextView_fontStyle, 0);
} finally {
if (this.a != null)
this.a.recycle();
}
if (!isInEditMode()) {
switch (fontStyle) {
case 1:
setTypeface(MyApplication.poppinsSemiBold);
break;
case 2:
setTypeface(MyApplication.helveticaNeueMedium);
break;
case 3:
setTypeface(MyApplication.poppinsRegular);
break;
default:
setTypeface(MyApplication.poppinsRegular);
break;
}
}
}
}
Use this in Your layout file
<TextViewPlus
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:fontStyle="poppinsRegular" />

Styling android.support.v7.preference.SeekBarPreference

First of all I am pretty new in programming Xamarin and Android. I have created a SeekbarPreference but some how they layout does not display all correctly. The value is dropping of from the box (see picture).
My styles.xml:
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<style name="MyTheme" parent="MyTheme.Base">
</style>
<style name="MyTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#EC6A1E</item>
<item name="colorAccent">#EC6A1E</item>
<item name="toolbarStyle">#style/custom_toolbar</item>
<item name="preferenceTheme">#style/PreferenceThemeOverlay.v14.Material.Fix</item>
</style>
<style name="custom_toolbar" parent="#style/Widget.AppCompat.Toolbar">
<item name="titleTextColor">#FFFFFF</item>
</style>
<style name="PreferenceThemeOverlay.v14.Material.Fix" parent="PreferenceThemeOverlay.v14.Material">
<item name="seekBarPreferenceStyle">#style/Preference.SeekBarPreference.Fix</item>
</style>
<style name="Preference.SeekBarPreference.Fix">
</style>
</resources>
Here is my settings.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.preference.PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.preference.SeekBarPreference
android:id="#+id/preference_range_seek_bar"
android:layout_height="wrap_content"
android:key="range"
android:title="Range"
android:summary="Here you can set the range of your location"
android:max="10000"
android:defaultValue="500" />
<android.support.v7.preference.SeekBarPreference
android:key="favRange"
android:title="Favorite Range"
android:summary="Here you can set the range of your Favorite location"
android:max="10000"
android:defaultValue="500" />
<android.support.v7.preference.Preference android:title="Title" android:summary="This is the summary">
</android.support.v7.preference.Preference>
</android.support.v7.preference.PreferenceScreen>
What I do not understand is how can I find which xml attributes I can use on the SeekBarPreference to fix this. When I look in Googles Documents I cannot find a description of xml attributes on this SeekBarPreference.
I know my theme is fuzzy as I played a lot with it. But when I have it working I will adjust this.
Hopefully someone could help me, or have an example..
Ran into the same issue. Here you go with the solution, testion on emulator running API 25:
Step 1, Create a new class that extends SeekBarPreference
public class CustomSeekBarPreference extends SeekBarPreference {
private TextView mSeekBarValueTextView;
public CustomSeekBarPreference(Context context,
AttributeSet attributeSet,
int i, int i1) {
super(context, attributeSet, i, i1);
}
public CustomSeekBarPreference(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
}
public CustomSeekBarPreference(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
public CustomSeekBarPreference(Context context) {
super(context);
}
#Override
public void onBindViewHolder(PreferenceViewHolder preferenceViewHolder) {
super.onBindViewHolder(preferenceViewHolder);
mSeekBarValueTextView = (TextView) preferenceViewHolder.findViewById(android.support.v7.preference.R.id.seekbar_value);
if (mSeekBarValueTextView != null) {
LayoutParams layoutParams = mSeekBarValueTextView.getLayoutParams();
layoutParams.height = LayoutParams.WRAP_CONTENT;
mSeekBarValueTextView.setLayoutParams(layoutParams);
}
}
}
In your preferences.xml replace the SeekBarPreference class name with the custom class name.
<com.google.xxx.view.CustomSeekBarPreference
android:key="cacheLimit"
android:title="#string/setting_cache_limit_title"
android:dependency="enableCaching"
android:defaultValue="20"
android:max="40"/>

How to set default parameters to custom UI Class?

I have created a Custom Class called RoundedButton that extends Button. I want to assign some default parameters. How to go about it?
There was no change after I implemented the xml codes below. Basically the style was not getting added by default. I don't know what I am missing.
in styles.xml
<resources>
<style name="AppTheme" parent="#android:style/Theme.Light">
<item name="RoundedButtonStyle">#style/CustomView</item>
</style>
<style name="CustomView">
<item name="android:clickable">true</item>
<item name="android:focusable">true</item>
<item name="android:focusableInTouchMode">true</item>
<item name="android:colorBackground">#color/transparent</item>
<item name="android:textColor">#color/blue</item>
<item name="android:windowBackground">#color/transparent</item>
<item name="android:background">#drawable/button_border</item>
<item name="android:gravity">center</item>
</style>
</resources>
in attrs.xml
<resources>
<attr name="RoundedButtonStyle" type="reference" />
</resources>
manifest:
android:theme="#style/AppTheme"
RoundButton.java
public RoundedButton(Context context) {
super(context);
ctx = context;
}
public RoundedButton(Context context, AttributeSet attrs) {
super(context, attrs, R.attr.RoundedButtonStyle);
ctx = context;
TypedArray attrsArray = context.obtainStyledAttributes(attrs, R.styleable.RoundedButtonAttrs, 0, 0);
initAttributesArray(attrsArray);
attrsArray.recycle();
initializeRoundedButton();
}
I have used this and this for trying to solve it.
EDIT: Earlier I had an issue that the background was light grey and did not change, I discovered the issue was because of a line of code that I had later in the UI Class.

Android: How to custom-declare XML namespace in styles.xml?

I'm trying to put the custom XML namespace in the styles.xml and inherit it in the layout. I don't know how to declare the custom XML namespace in the styles.xml as I do in layout xml (e.g. xmlns:app="http://schemas.android.com/tools").
How do I use custom XML namespace in the styles.xml?
What I have:
The font asset, ReallyCoolFont.ttf is saved in the asset/fonts.
my_layout.xml:
<TextView
<!-- more attributes here -->
app:customFont="fonts/ReallyCoolFont.ttf"
<!-- more attributes here -->
</TextView>
styles.xml:
<style name="CoolTextView">
<!-- more items here -->
<!-- more items here -->
</style>
What I'd like to have:
my_layout.xml:
<TextView
<!-- more attributes here -->
style="#style/CoolTextView
<!-- more attributes here -->
</TextView>
styles.xml:
<style name="CoolTextView">
<!-- more items here -->
<item name="app:customFont">ReallyCoolFont.ttf</item>
<!-- more items here -->
</style>
Error I get:
Error:(1403, 21) No resource found that matches the given name: attr 'app:customFont'.
You need to define an attribute for your fonts in attr.xml file in res folder:
<attr name="myfonts" format="string" />
And 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>
Then styles can be declared:
<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>
You don't need any prefixes, it will work without them. This is code from one of my projects, which works just fine
<style name="defaultTriangle">
<item name="triangleColor">#FF33B5E5</item>
<item name="triangleStrokeColor">#android:color/black</item>
<item name="triangleStrokeWidth">3dp</item>
</style>
<si.kseneman.views.Triangle
style="#style/defaultTriangle"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:padding="10dp"
android:rotation="0"
/>
I've done next for custom font
CustomTextView
public class KlavikaTextView extends TextView {
private final static int KLAVIKA_BOLD = 0;
private final static int KLAVIKA_BOLD_ITALIC = 1;
private final static int KLAVIKA_LIGHT = 2;
private final static int KLAVIKA_LIGHT_ITALIC = 3;
private final static int KLAVIKA_MEDIUM = 4;
private final static int KLAVIKA_MEDIUM_ITALIC = 5;
private final static int KLAVIKA_REGULAR = 6;
private final static int KLAVIKA_REGULAR_ITALIC = 7;
public KlavikaTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
parseAttributes(context, attrs);
}
public KlavikaTextView(Context context, AttributeSet attrs) {
super(context, attrs);
parseAttributes(context, attrs);
}
public KlavikaTextView(Context context) {
super(context);
}
private void parseAttributes(Context context, AttributeSet attrs) {
TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.KlavikaTextView);
// The value 0 is a default, but shouldn't ever be used since the attr is an enum
int typeface = values.getInt(R.styleable.KlavikaTextView_typeface, KLAVIKA_REGULAR);
// You can instantiate your typeface anywhere, I would suggest as a
// singleton somewhere to avoid unnecessary copies
switch (typeface) {
case KLAVIKA_BOLD:
setTypeface(App.klavikaBold);
break;
case KLAVIKA_BOLD_ITALIC:
setTypeface(App.klavikaBoldItalic);
break;
case KLAVIKA_LIGHT:
setTypeface(App.klavikaLight);
break;
case KLAVIKA_LIGHT_ITALIC:
setTypeface(App.klavikaLightItalic);
break;
case KLAVIKA_MEDIUM:
setTypeface(App.klavikaMedium);
break;
case KLAVIKA_MEDIUM_ITALIC:
setTypeface(App.klavikaMediumItalic);
break;
case KLAVIKA_REGULAR_ITALIC:
setTypeface(App.klavikaRegularItalic);
break;
case KLAVIKA_REGULAR:
default:
setTypeface(App.klavikaRegular);
break;
}
}}
Then in values I've created attr.xml
<!-- Define the values for the attribute -->
<attr name="typeface" format="enum">
<enum name="klavika_bold" value="0" />
<enum name="klavika_bold_italic" value="1" />
<enum name="klavika_light" value="2" />
<enum name="klavika_light_italic" value="3" />
<enum name="klavika_medium" value="4" />
<enum name="klavika_medium_italic" value="5" />
<enum name="klavika_regular" value="6" />
<enum name="klavika_regular_italic" value="7" />
</attr>
<!--
Tell Android that the class "KlavikaTextView" can be styled,
and which attributes it supports-->
<declare-styleable name="KlavikaTextView">
<attr name="typeface" />
</declare-styleable>
Next created the style
<style name="TextView.Example">
<item name="typeface">klavika_bold</item>
</style>
This style you can use for your xml Layouts
style="#style/TextView.Example"
<?xml version="1.0" encoding="utf-8"?>
<resources
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.my.project">
<style name="my_style"> <item name="custom:tag">some_value</item> </style>
</resources>
you are trying to apply XML namespacing to an attribute value, which won't work. In this case, you should specify the package name directly, like this:
<style name="my_style"> <item name="com.my.project:tag">some_value</item> </style>
Fast solution via code!
String pathFont = "fonts/ReallyCoolFont.ttf";
TextView text = (TextView) findViewById(R.id.TextView1);
Typeface fontFace = Typeface.createFromAsset( getAssets(), pathFont );
text.setTypeface( fontFace );
Third-party libraries , solve the problem, in XML!
1 - https://github.com/leok7v/android-textview-custom-fonts
2 - https://github.com/ragunathjawahar/android-typeface-textview
My suggestion
You will have other needs, and for each component
you will have to customize a class.
Another problem you have other layouts and N TextView components
for maintenance you will have a lot of work .
I use this method in projects in the OnCreate of my activity
if I need to change the font I have to do this
only in the OnCreate method of each activity .
private static final String FONT = "ReallyCoolFont.ttf";
public static void allTextView(final Context context, final View root) {
String fontPath = FONT;
try {
if (root instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) root;
int childCount = viewGroup.getChildCount();
for (int i = 0; i < childCount; i++)
allTextView(context, viewGroup.getChildAt(i) );
} else if (root instanceof TextView)
((TextView) root).setTypeface(Typeface.createFromAsset(context.getAssets(), fontPath));
} catch (Exception e) {
e.printStackTrace();
}
}
// call in OnCreate Activity
allTextView(this, findViewById(R.layout.main) );
The custom attributes are defined using <declare-styleable> tags; usually the file is called attrs.xml. The namespace declaration will have your app's package name in it.
The whole process is described here: Creating a View Class | Android Developers

Apply style for button group in Android

In my Android application I need to apply style for a group of buttons, instead of styling each button individual. Something like this:
<?xml version="1.0" encoding="utf-8"?>
<!-- put here style="#ststyle/Button_Style" -->
<Button android:id="#+id/button1" android:text="#string/b01" />
<Button android:id="#+id/button2" android:text="#string/b02" />
<Button android:id="#+id/button4" android:text="#string/b03" />
<!-- end style -->
You can write the style for button like this ;
style_btn.xml
<style name="style_btn" parent="Wrap">
<item name="android:background">#drawable/btn_bg</item>
<item name="android:gravity">center</item>
<item name="android:textColor">#android:color/white</item>
<item name="android:textStyle">bold</item>
<item name="android:layout_marginTop">4dp</item>
<item name="android:minWidth">90dp</item>
</style>
apply that style to your button :
<Button
android:id="#+id/attach_file"
style="#style/style_btn"
android:layout_centerVertical="true"
android:background="#drawable/orange_bg"
android:drawablePadding="10dp"
android:drawableRight="#drawable/attach"
android:text="#string/str_email_attach" />
If you need the style to all of the buttons in your application, mention in your App theme style, Then no need to apply for every button.
<style name="YourTheme" parent="android:Theme.Light">
<item name="android:buttonStyle">#style/Button</item>
</style>
If you need the style to particluar button , then apply to every button
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/Button"
android:text="Button" />
I know I'm late joining the party but I stumbled across this when trying to figure out the same problem myself.
What I did was:
Depending on how may button groups you have (say 3 for example) you need to subclass button and create three custom button classes (see below)
//Custom button 1
public class CustomButton1 extends Button {
public CustomButton1(Context context, AttributeSet attrs) {
super(context, attrs, R.attr.attrStyle1);
}
public CustomButton1(Context context, AttributeSet attrs, int defStyle) {
super(context, null, R.attr.attrStyle1);
}
}
//Custom button 2
public class CustomButton2 extends Button {
public CustomButton2(Context context, AttributeSet attrs) {
super(context, attrs, R.attr.attrStyle2);
}
public CustomButton2(Context context, AttributeSet attrs, int defStyle) {
super(context, null, R.attr.attrStyle2);
}
}
//Custom button 3
public class CustomButton3 extends Button {
public CustomButton3(Context context, AttributeSet attrs) {
super(context, attrs, R.attr.attrStyle3);
}
public CustomButton3(Context context, AttributeSet attrs, int defStyle) {
super(context, null, R.attr.attrStyle3);
}
}
You can see from the custom classes I have passed a custom attr. These I define in my styles.xml and use them as reference. See my styles.xml below:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
<style name="theme1">
<item name="#attr/attrStyle1">#style/CustomButton1</item>
<item name="#attr/attrStyle2">#style/CustomButton2</item>
<item name="#attr/attrStyle3">#style/CustomButton3</item>
<item name="android:background">#color/warning_yellow_colour</item>
</style>
<style name="CustomButton1" parent = "#android:style/Widget.Button">
<item name="android:textColor">#color/white_colour</item>
<item name="android:padding">20dp</item>
<item name="android:background">#color/banner_background_sensor_colour</item>
</style>
<style name="CustomButton2" parent = "#android:style/Widget.Button">
<item name="android:textColor">#color/white_colour</item>
<item name="android:padding">20dp</item>
<item name="android:background">#color/button_red_colour</item>
</style>
<style name="CustomButton3" parent = "#android:style/Widget.Button">
<item name="android:textColor">#color/white_colour</item>
<item name="android:padding">20dp</item>
<item name="android:background">#color/text_blue_colour</item>
</style>
<attr name="attrStyle1" format="reference"/>
<attr name="attrStyle2" format="reference"/>
<attr name="attrStyle3" format="reference"/>
By linking the style to the attr, you then apply that style to your custom class, which you can then duplicate as many times as needed
CustomButton1 theme1 = (CustomButton1)findViewById(R.id.theme1);
CustomButton2 theme2 = (CustomButton2)findViewById(R.id.theme2);
CustomButton3 theme3 = (CustomButton3)findViewById(R.id.theme3);
Hopefully this is of benefit to someone!

Categories

Resources