LoginSignup
3
4

More than 5 years have passed since last update.

fragmentのタブのアイコン画像のサイズをカスタマイズする

Last updated at Posted at 2016-09-28

タブに画像を設定する場合

デフォルトで24dpのサイズしか適用されない。

FragmentActivity.java

TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);

// タブに画像をセット
tabLayout.getTabAt(0).setIcon(R.drawable.ic_photo_camera_black_24dp);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_line_weight_black_24dp);


タブの画像サイズを変更する場合

setIconではなく、→ setCustomView ←でlayoutファイルを指定。

FragmentActivity.java

TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);

tabLayout.getTabAt(0).setCustomView(R.layout.design_fragment_icon_camera);
tabLayout.getTabAt(1).setCustomView(R.layout.design_fragment_line_weight);

1番めのタブ画像用xml

design_fragment_icon_camera.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:scaleType="centerInside"
    android:src="@drawable/image_icon_camera"
    />

2番めのタブ画像用xml

design_fragment_icon_line_weight.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:scaleType="centerInside"
    android:src="@drawable/image_icon_line"
    />

おまけ

setCustomViewでセットするxmlファイルのImageViewですが、

design_fragment_icon_camera.xml
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:scaleType="centerInside"
    android:src="@drawable/image_icon_camera"
    />

srcCompatで、svg画像もできるかなと思ったのですが、
何故かsvg画像だと、画像が表示されませんでした。。
(ic_attachment_black_24dp.xmlがsvg画像)

design_fragment_icon_camera.xml

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:scaleType="centerInside"
    app:srcCompat="@drawable/ic_attachment_black_24dp"
    android:tint="@color/colorBlack"
    />

参考にさせて頂いたサイト様 m( _ _ )m

https://blog.4star.link/?p=1784
http://qiita.com/ryohey/items/df96d3f7e56756962380

3
4
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
3
4