【问题标题】:How can I get an image button's dimensions to make sense in android?如何让图像按钮的尺寸在 android 中有意义?
【发布时间】:2011-03-11 02:14:02
【问题描述】:

首先,我可以说,我发现布局 android UI 是一种令人沮丧的体验吗?我曾经认为 XML 布局简单、干净、很棒,但每次我尝试用它做任何事情时,我都会花费数小时尝试做最简单的事情!

在这个特定的实例中,我正在尝试制作一个简单的水平条,其中包含一个固定大小的图像按钮,在它的右侧和左侧我想要一个占据其余可用宽度的 ImageView。我一直在 UI 中看到类似的结构:搜索时出现在屏幕顶部的搜索框、文本区域和用于撰写文本/googletalk 消息的发送按钮等。

我尝试了水平线性布局和相对布局,但我无法让按钮在任何一个中看起来都正确。我最近的尝试有以下布局代码:

看起来像这样:

使用 hiearchyviewer 表示 imageview 和按钮的高度相同(45px)。它显示的视图尺寸和位置正是我正在寻找的。相同的高度(当然宽度不同,因为 ImageView 更宽)。它们彼此紧挨着,以相对布局为中心。然而,在屏幕上绘制的按钮显然没有占用完整的 ImageButton 视图。我认为用于 ImageButton 背景的 android 系统 9patch drawable 有点奇怪。但我知道什么?无论我尝试什么,我都无法让它看起来正确。

【问题讨论】:

    标签: android layout position imagebutton dimensions


    【解决方案1】:

    您是如何设置您的RelativeLayout 的?尝试这样设置:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent" android:layout_height="wrap_content">
        <ImageButton android:layout_width="wrap_content" android:src="@drawable/icon" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:id="@+id/imgButton"></ImageButton>
        <ImageView android:id="@+id/imageView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:src="@drawable/red_button" android:scaleType="fitXY" android:layout_alignBottom="@+id/imgButton" android:layout_alignTop="@+id/imgButton" android:layout_toLeftOf="@+id/imgButton"></ImageView>        
    </RelativeLayout>
    

    希望这会有所帮助。

    【讨论】:

    • 正如我之前提到的那样,该布局会导致层次结构查看器中视图的正确尺寸和位置,但在设备上查看时按钮仍然没有正确的尺寸。从那以后,我决定为按钮背景制作自己的九个补丁,这似乎奏效了。看起来系统九补丁按钮可绘制在图像本身的底部有一些填充。
    【解决方案2】:

    如果尺寸正是您想要的,那么在 ImageButton 和 ImageView 中,使用 android:scaleType="fitXY" 并检查。

    对于简单的情况,我可能会使用带有水平方向的线性布局,其中包含两个具有适当权重的按钮。

    【讨论】:

    • 你会认为它会这么简单,不是吗?我现在已经设法让按钮背景的大小合适,但我无法让图像在 ImageButton 中居中,它总是出现在顶部。我试过 fitXY 还是不居中。
    猜你喜欢
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 2014-03-07
    相关资源
    最近更新 更多