我有一个RelativeLayout,它包含一个ImageView和一个ImageButton。 ImageView充当背景图像的容器。现在我正在尝试将按钮设置在固定位置,以便它始终显示在背景图像上的相同位置。
这是我正在使用的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout1" android:layout_height="match_parent"
android:layout_width="match_parent" android:gravity="center_horizontal">
<ImageView android:src="@drawable/bg_1" android:id="@+id/imgView"
android:adjustViewBounds="true" android:layout_height="match_parent"
android:layout_width="match_parent" />
<ImageButton android:layout_width="120dp"
android:background="@drawable/button_1" android:layout_height="30dp"
android:id="@+id/imgButton" android:layout_marginLeft="100dp"
android:layout_marginTop="170dp" />
</RelativeLayout>
正如你所看到的,我已经尝试使用dp作为单位来定位带有左/上边距的按钮,但这不起作用。由于背景图像按比例缩小/缩小,因此位置必须以某种方式动态。
我理解绝对定位(x- / y-position的像素值)在Android上无效,就像here所解释的那样。我仍然需要解决这个问题并且不确定如何。
我是否必须计算left- / top-margin的值(不知道会是怎样)然后用这样的东西设置它们?
final float density = getResources().getDisplayMetrics().density;
int width = (int)((float)120 * density);
int height = (int)((float)120 * density);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(width, height);
rlp.leftMargin = newMargin;
rlp.topMargin = newTopMargin;
ImageButton imgButton = (ImageButton) findViewById(R.id.imgButton);
imgButton.setLayoutParams(rlp);
希望我没有忘记一些事情......
//编辑: 我在想,问题的原因可能是,缩放后的图像具有不同的“边框”,具体取决于屏幕尺寸。 在HVGA屏幕上使用1:1.6比例的图像时,左右两侧有黑条,而在WVGA屏幕上,条形图位于左侧。考虑到我正在使用默认缩放。如果有必要,我会调查并重新发布......
答案 0 :(得分:0)
为什么要进行缩放?因为不同设备上的dpi不同?对于不同的dpi设置,您有不同的drawabled吗?如果它不仅仅是dpi问题并且您想要自由地缩放该背景图像,那么您无法使用标准布局来完成工作。你应该实现一个自定义的。