LoginSignup
8
5

More than 5 years have passed since last update.

TextViewにVector drawableを使う

Posted at

AndroidとVector

Androidでは2年ぐらい前からVector形式を扱えるようになりました。
InstantAppが登場していることから分かる通り、現在のモバイルアプリにおいてアプリの容量削減は必須となっています。

drawable (left|top|right|bottom)

突然ですがこのようなレイアウトをどのようにしますか?

スクリーンショット 2017-06-07 0.27.16.png

簡単に考えるならLinearLayoutでorientationをhorizontalにして、ImageViewとTextViewを並べる方法がありますが、
Androidにはdrawable(left|top|right|bottom)というTextViewにdrawableを簡単にセット出来るAPIがあります。

TextViewには前述のVector形式のファイルもセットすることが出来ます。
ただし、Lollipopより下のOSバージョンで使う場合はselectorで囲ってStateListを作る必要があります。

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

2017年現在で min sdk versionを21に出来る商用アプリはまだ少ないと思いますので、
TextViewにVector Drawableを使いたい場合はdrawableの二重管理になってしまいます。

私が担当しているサービスでもアイコンは全てVector Drawableのため二重管理を避けるために
CompoundIconTextViewというライブラリを作りました。

中身はとてもシンプルでresourceファイルからBitmapを作成してDrawable形式に変換しています。


private Drawable resource2VectorDrawable(@DrawableRes final int resourceId, @ColorInt final int iconColor,
                                             final int iconWidth, final int iconHeight) {
        final Context context = getContext();
        final Drawable drawable = AppCompatResources.getDrawable(context, resourceId);

        if (drawable == null) {
            throw new Resources.NotFoundException("Resource not found : %s." + resourceId);
        }

        // See if we need to 'fix' the drawableLeft
        fixDrawable(drawable);
        // Set color
        DrawableCompat.setTint(drawable, iconColor);
        DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_IN);
        // Resize Bitmap
        return new BitmapDrawable(context.getResources(),
                Bitmap.createScaledBitmap(drawable2Bitmap(drawable, iconWidth, iconHeight), iconWidth, iconHeight, true));
    }

  private static Bitmap drawable2Bitmap(final Drawable drawable, final int iconWidth, final int iconHeight) {
        final Bitmap bitmap = Bitmap.createBitmap(iconWidth, iconHeight, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return bitmap;
    }

TextViewのdrawableではiconの縦横サイズを自由に決める事が出来ませんが、自由に変更出来るようになっています。
アイコンの色も自由に変えられるようになっているので、使い勝手は良いと思います。
4系以下でvectorの色を変えたい場合はgradleに以下の記述が必要なのでお気をつけ下さい。

android {
  defaultConfig {
    vectorDrawables.useSupportLibrary = true
  }
}

CompoundIconTextView : https://github.com/AAkira/CompoundIconTextView

こういうのはsupport libraryで対応して欲しいですね (´ω`)

8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5