我尝试在 TabLayout 中为选项卡设置图标,但图标的大小始终无法正确缩放。起初,我尝试了 setIcon() 方法,但选项卡上生成的图标尺寸非常小。
在 StackOverflow 上查看后,人们建议使用 setCustomView() 在 TabLayout 上显示图标。执行此操作后,图像大小会扩展以填充每个分配的选项卡空间,但根据设备的 Android 版本,有时图像会显得稍微拉伸(stretch)。
如左侧所示,图像被拉伸(stretch),而右侧图像则正确缩放。我将选项卡 View 设置为 ImageView 的 View ,目前我将 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时,我才开始遇到这些问题)
最佳答案
- 使用
RelativeLayout
作为ImageView
的容器。 - 使用
ImageView
宽度和高度作为wrap_content
而不是match_parent
。 - 向
ImageView
添加属性android:layout_centerInParent="true"
- 无需使用
android:scaleType="fitCenter"
试试这个:
<?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>
仅供引用,请确保您的 drawable-XXXXX
文件夹中拥有所有分辨率
的图像
。
希望对你有帮助~
关于java - TabLayout 图标大小未正确缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43553130/