嗨,我正在开发一个Android应用程序,我有一些布局,我希望有一个图像填充横向模式 screen-width
. 最重要的是,我想在特定的地方有一些按钮 .
我使用了 scrollview
(因为如果图像填满屏幕的宽度,图像不适合高度),并且内部有相对布局 .
在那个相对布局中,我放了 imageview
和按钮 . 图像填充宽度并包裹高度的内容 . 通过在相对布局内设置左边距和上边距来放置按钮 .
我测试的手机上的一切都很好看,但是当我在不同的设备(其他屏幕尺寸和密度)上进行测试时,所有按钮都位于错误的位置并且不再足够大 .
我怎样才能改变这一点,以便所有比例都保持不变?与图像相比,按钮必须位于完全相同的位置,并且必须具有相同的尺寸 .
我的代码:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/svCentralAmerica"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true" >
<RelativeLayout
android:id="@+id/rlCentralAmerica"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/ivCentralAmerica"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:src="@drawable/mapcentralamerica" />
<Button
android:id="@+id/mexu"
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="33dp"
android:background="@drawable/usa_y"
android:onClick="onCountryClick"
android:paddingTop="3dp"
android:scaleType="fitCenter"
android:tag="1;U"
android:text="2"
android:textColor="@color/Black"
android:textSize="15sp"
android:textStyle="bold" />
<Button
android:id="@+id/mexr"
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_alignTop="@id/mexu"
android:layout_marginLeft="4dp"
android:layout_toRightOf="@id/mexu"
android:background="@drawable/russia_n"
android:onClick="onCountryClick"
android:paddingTop="18dp"
android:scaleType="fitCenter"
android:tag="1;R"
android:text="3"
android:textColor="@color/Red"
android:textSize="15sp"
android:textStyle="bold" />
</RelativeLayout>
</ScrollView>
2 回答
我实际上已经完成了你的想法 . 不幸的是,如果您想要精确控制任何屏幕尺寸的定位,以及精确的宽高比,那么您将不得不以编程方式定位资源 . 如果你使用xml,你可以非常接近,但不会有精确的定位控制 . 对于初学者来说,以编程方式定位可能很乏味 . 因为你只是在这里和那里定位几个按钮,所以不应该太麻烦 .
我是怎么做到的:以编程方式获取screenwidth和screenheight . 然后计算按钮的纵横比 . 接下来,计算按钮相对于屏幕宽度和屏幕高度的位置(这将是%) . 有了所有这些信息,您应该能够在任何具有特定方向的屏幕尺寸上将按钮准确定位在您想要的位置 . 我建议将其他所有内容放在xml上,并仅以编程方式执行按钮 . 在方向改变时,您需要再次重新计算所有内容,这可能很烦人 . 我建议您坚持使用1个方向,以后可能支持多个方向 .
我使用这些辅助函数根据屏幕高度和宽度的百分比移动我的按钮 . 首先,我将屏幕布局为图形布局的320 x 480屏幕,以创建xml,然后在onCreate方法中移动按钮 .
这是我使用的进口:
以下是在onCreate中移动按钮的调用:
以下是辅助函数:
我希望它对某人有帮助 .