java - TabLayout 图标大小未正确缩放

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

我尝试在 TabLayout 中为选项卡设置图标,但图标的大小始终无法正确缩放。起初,我尝试了 setIcon() 方法,但选项卡上生成的图标尺寸非常小。

enter image description here

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

enter image description here

如左侧所示,图像被拉伸(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时,我才开始遇到这些问题)

最佳答案

  1. 使用RelativeLayout作为ImageView的容器。
  2. 使用 ImageView 宽度和高度作为 wrap_content 而不是 match_parent
  3. ImageView 添加属性 android:layout_centerInParent="true"
  4. 无需使用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/

相关文章:

java - "forClass"类中有一个名为 "DetachedCriteria"的静态方法,但我无法使用它

java - 其他面板的背景图片问题

java - 用于负整数和正整数的 DocumentFilter

android - 在gradle同步中突然出现错误-构建工具版本27.0.1和支持版本27.0.1等在android studio项目中找不到

android - 没有通过 REST 调用接收 json 数据

android - 以编程方式动态地将 View 添加到 FragmentActivity

android - 为什么 ViewPager 高度 match_parent 不起作用?

java - 这个带有 for 循环的递归调用的 Big-O 时间复杂度是多少

android - iOS 和 Android 之间的加密数据传输(ByteArray 或 Base64EncodedString 兼容性问题)

android - ListView onItemClick 区域在手机和平​​板电脑上不同