TabLayout图标大小无法正确缩放

时间:2017-04-21 22:49:27

标签: java android android-layout android-imageview android-tablayout

我正在尝试在TabLayout中为我的标签设置图标,但图标的大小会不正确地缩放。起初,我尝试了setIcon()方法,但是选项卡上的结果图标大小非常小。

enter image description here

在浏览StackOverflow之后,人们建议使用setCustomView()代替在TabLayout上显示图标。执行此操作后,图像大小会扩展以填充每个分配的选项卡空间,但根据设备的Android版本,有时图像会略微拉伸。

enter image description here

正如您在左侧所见,图像被拉伸,而图像在右侧正确缩放。我正在设置选项卡视图的视图是一个ImageView,我目前将scaleType设置为fitCenter。

<?xml version="1.0" encoding="utf-8"?>
<ImageView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tab_icon"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:scaleType="fitCenter"/>

我已经尝试将scaleType设置为fitXY,但是图标图像不会展开以占据所有可用的标签空间,并且看起来像第一个图像。非常感谢任何帮助,谢谢!

(注意:不确定这有多重要,但是当我将compileSdkVersion设置为23时,使用setIcon()显示选项卡图标没有问题。只有当我将compileSdkVersion设置为25时才开始出现这些问题)< / p>

1 个答案:

答案 0 :(得分:0)

  1. 使用RelativeLayout作为ImageView的容器。
  2. ImageView的宽度和高度设为wrap_content,而不是match_parent
  3. 将属性android:layout_centerInParent="true"添加到ImageView
  4. 无需使用android:scaleType="fitCenter"
  5. 试试这个:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    
        <ImageView
            android:id="@+id/tab_icon"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_centerInParent="true" />
    
    </RelativeLayout>
    

    仅供参考,确保images个文件夹中的所有resolution都有drawable-XXXXX

    希望这会有所帮助〜