Icon fonts are useful, aren't they? Icon fonts allow you to display icon images in your text. In other words, you can easily create icons + text buttons. However, since it is displayed as one element, there is a problem that different sizes cannot be used for the text and the icon, and the baseline is aligned between the icon and the text.
Android buttons can display icons inside the buttons by using the drawableLeft and drawableRight attributes. It seems that this attribute can solve the above problem, but it cannot be used as it is because it is necessary to specify the image.
Therefore, I will explain how to convert the icon font to a drawable vector and display it as an icon.
Iconics is used as a library for using icon fonts.
If you specify the drawable_icon_font_left attribute as shown below, the icon will be displayed nicely.
<Button
android:text="{faw-android} android"
/>
<Button
android:text="android"
app:drawable_icon_font_left="@{`faw_android`}"
/>
Add the following settings in ** build.gradle **. Here, we will use AwesomeFont as an example.
android {
...
dataBinding {
enabled = true
}
}
dependencies {
...
compile "com.mikepenz:iconics-core:2.8.2@aar"
compile 'com.mikepenz:fontawesome-typeface:4.7.0.0@aar'
}
Add the following settings to the Activity and Fragment to be used.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
LayoutInflaterCompat.setFactory(getLayoutInflater(), new IconicsLayoutInflater(getDelegate()));
super.onCreate(savedInstanceState);
DataBindingUtil.setContentView(this, R.layout.activity_main);
}
}
** Define the drawable_icon_font_left ** attribute.
Within the method, it will generate a Drawable from the specified characters. At that time, you can set the same color as the text or set the icon size a little larger than the text size according to your preference.
public class BindingAdapterManager {
@BindingAdapter("drawable_icon_font_left")
public static void setDrawableIconFontLeft(final Button button, final String icon) {
final Context context = button.getContext();
final IconicsDrawable iconicsDrawable = new IconicsDrawable(context)
.icon(FontAwesome.Icon.valueOf(icon))
.color(button.getCurrentTextColor())
.sizePx((int)(button.getTextSize() * 1.25));
button.setCompoundDrawables(iconicsDrawable, null, null, null);
}
}
I have a project that works on Drawable-Icon-Font @ github.
This tip was born during the development of "a site where you can buy and sell smartphone photo materials Snapmart". Unfortunately, the Android version is still under development and is not available yet. If you have an iPhone, please download and use it! Snapmart App (iOS)
Recommended Posts