ImageView顶部的放置按钮可使用不同的屏幕尺寸进行拉伸

问题描述 投票:3回答:1

我有一个图像(match_parent),其中包含2个包含选项的矩形。我试图在图像上方放置2个透明按钮,以便在图像上单击会导致动作。但是,我试图支持多种屏幕尺寸,因此尽管我能够使用布局边距来调整特定分辨率智能手机的按钮中的矩形,但测试平板电脑完全失败。

我如何放置与一直延伸以填充不同屏幕尺寸的图像一致的按钮。

现在使用dp的非常简单的布局代码无法正常工作

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/banner"
    android:background="@drawable/banner"
    android:contentDescription="@string/banner" />

<Button
    android:layout_width="120dp"
    android:layout_height="90dp"
    android:id="@+id/vs_computer"
    android:layout_marginTop="135dp"
    android:layout_marginLeft="135dp"
    android:alpha="0"
    android:clickable="true"
    android:shadowColor="@android:color/transparent"
    android:singleLine="true" />

<Button
    android:layout_width="120dp"
    android:layout_height="100dp"
    android:id="@+id/multiplayer"
    android:layout_marginTop="260dp"
    android:layout_marginLeft="135dp"
    android:alpha="0"
    android:clickable="true"
    android:shadowColor="@android:color/transparent"
    android:singleLine="true" />

我正在使用的临时图像:options(来源:trillian.im

android android-layout imageview android-button
1个回答
0
投票

您可以从背景图像中省略两个按钮图形(只需留一个空白),然后将它们分开显示。然后,您可以将它们放在两个ImageButton上。这解决了必须完美排列绝对像素的直接问题。

要确定这些按钮的大小和位置,请确定其左/右和上/下边距占屏幕宽度和高度的百分比。然后,您可以创建自定义布局(ViewGroup的子类)并实现onLayout(...)方法,方法是将这两个按钮应用于您的视图大小,将这两个按钮放置在背景图像的所需区域内。

该自定义ViewGroup可能看起来像这样:

public class Blah extends ViewGroup {

    Button b1;

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        b1 = (Button) findViewById(R.id.button_1);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        // In dimensions XML: <fraction name="button_margin_horizontal">20%p</fraction>
        int left = (int) getResources().getFraction(R.fraction.button_margin_horizontal, 0, getWidth());
        int right = getWidth() - left;
        int buttonHeight = b1.getMeasuredHeight();
        b1.layout(left, 0, right, buttonHeight);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.