mohsin raza February 2016

How to use font icon (font-awesome) in XML selector

Is it possible to use font icon in selector instead of drawable ?

Thanks

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/menu_home_press" android:state_pressed="true"></item>
    <item android:drawable="@drawable/menu_home"></item>
</selector>

Answers


driodev February 2016

You can use font-awesome icons as follows :

1 - Copy font-awesome font file to your assets directory

2 - Found the character entities for icons I wanted, using this page

3 - Create entry in strings.xml for each icon. Eg:

<string name="icon_eg">&#xf13d;</string>

4 - Load the font in onCreate method and set it for the appropriate Views:

Typeface font = Typeface.createFromAsset( getAssets(), "fontawesome-webfont.ttf" );
...
Button button = (Button)findViewById( R.id.like );
button.setTypeface(font);

Don't forget to reference the string in view.

<Button
     android:id="@+id/my_btn"
     style="?android:attr/buttonStyleSmall"
     ...
     android:text="@string/icon_eg" />

check this link for more info.

you can't use it as selector. but you can dynamically change the icons.


mohsin raza February 2016

I changed text color in selector instead of drawable. Its working fine.

Create MyTextView class which extends TextView

public class MyTextView extends TextView {

    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MyTextView(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context) {
        Typeface tf = Typeface.createFromAsset(context.getAssets(),
                "fontawesome-webfont.ttf");
        setTypeface(tf);
    }
}

Create text_color_selector.xml selector

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="#ff0000" android:state_pressed="true" />
    <!-- pressed -->
    <item android:color="#ff0000" android:state_focused="true" />
    <!-- focused -->
    <item android:color="#000000" />
    <!-- default -->
</selector>

And then use it in you layout

 <com.example.mohsin.myapplication.MyTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="50sp"
        android:clickable="true"
        android:textColor="@drawable/text_color_selector"
        android:text="\uF242">

    </com.example.mohsin.myapplication.MyTextView>

Post Status

Asked in February 2016
Viewed 3,901 times
Voted 4
Answered 2 times

Search




Leave an answer