android - ImageButton 在 gridlayout 中自动调整大小

标签 android xml layout

我在问这个(可能)非常简单的问题,因为我自己无法弄清楚,而且谷歌搜索超过一个小时也没有给我正确的结果。 所以问题是:当我的图片非常大时(简而言之:我将 16xImages 作为 src 加载到 buttonImages ,每个图像都是 640x640,我想让网格布局中的 16 个按钮与网格布局宽度/高度和列/行数相比进行缩放)。我希望这可以用 XML 编写,因为我不想重构我的 Java 代码:/

附言。我是 Android 编程新手

Ps2.这是我的 GridLayout with button example ,但它是完全错误的:/

<GridLayout
    android:id="@+id/GridLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnCount="4"
    android:rowCount="4"
    tools:context=".GridXMLActivity"
    android:layout_below="@+id/Tx1"
    android:layout_above="@+id/restart"
    android:layout_marginBottom="50sp"
    android:layout_marginTop="50sp"
    >


    <ImageButton
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent"
        android:src="@drawable/clear"
        android:id="@+id/But1"
        android:scaleType="fitXY"
        android:onClick="but1"

        />

[编辑] 我什至做了这样的布局,但是有一些问题。第一个是我的网格布局根本无法缩放!(所以当我使用较低或较高分辨率的屏幕时,它不适合)。这就是为什么我想让这个按钮可以调整大小(在这个屏幕上每个按钮的宽度和高度都是 60sp,我知道它不应该) 另一个问题是我正在处理按钮背景,我想把它设为 src。 一般来说,我想实现与屏幕上相同的效果,但要以其他/更灵活的方式实现(因此分辨率和方向不会影响我的图形用户界面及其元素的大小)。如果你需要整个 XML 文件,我会把它贴在这里,但它有点乱,因为我复制粘贴了 16 次 Image Button enter image description here

最佳答案

如果您想要缩放某些东西,保持纵横比,并且您将一个维度设置为 match_parent,另一个必须是 wrap_content

因此,假设您希望按钮始终适合宽度但保持正确的纵横比:

<ImageButton
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    ... />

要使所有项目适合网格而不是所有项目适合其图像,您应该使用权重。 Weight with grid layout需要API21之前的支持库

<GridLayout ...
    android:columnCount="2">

    <ImageButton
        app:layout_gravity="fill"
        app:layout_columnWeight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        ... />

    ...

关于android - ImageButton 在 gridlayout 中自动调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42986249/

相关文章:

插入后Android SQLite查询不返回数据

arrays - 如何强制 jettison 写一个数组,即使数组中只有一个元素?

xml - Shell 脚本,解析 XML 片段

android - 如何在屏幕的特定位置对齐 View ,在多种屏幕分辨率下保持一致?

html - 如何进行这样的布局?滚动元素的动态高度

android - 获取 "Connecting over ADB to localhost:5277...failed"

安卓 : creating drawables with CSS input

android - 如何在 FFmpeg 创建的水印上应用自定义字体

java - 在 Android 中验证 XML 架构

html - 如何在 HTML 中制作底部固定位置菜单?