使用ImageView的RelativeLayout - 计算元素的位置

时间:2013-08-14 08:46:37

标签: android-layout

我的Android代码有问题。我有以下代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="vertical">

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:layout_centerVertical="true"
    android:src="@drawable/pdf" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/imageView1"
    android:layout_alignLeft="@+id/imageView1"
    android:text="Test-Label"
    android:textColor="@color/red" />

</RelativeLayout>

我想将textview现在放在我的imageview中并使用以下代码

ImageView iv = (ImageView) findViewById(R.id.imageView1);

int width = iv.getWidth();
int height = iv.getHeight();

float percentMarginTop  = 58f;
float percentMarginLeft     = 65f;
float percentTextSize   = 3f;

float marginTop     = height / 100f * percentMarginTop;
float marginLeft    = width / 100f * percentMarginLeft;

TextView tv = (TextView) findViewById(R.id.textView1);
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, Math.round(height / 100f * percentTextSize));
RelativeLayout.LayoutParams lpTv = (RelativeLayout.LayoutParams) tv.getLayoutParams();
lpTv.topMargin = Math.round(marginTop);
lpTv.leftMargin = Math.round(marginLeft);

所以我想用元素的位置来计算imageview的实际宽度和高度的百分比值。因此在我看来,元素应该在每个没有携带密度(ldpi,mdpi,xhdpi,...)和屏幕尺寸(小,正常,大,xlarge,......)的设备上正确定位,但是方便的位置(4&#34;)在平板电脑等其他设备上是正确但不正确的(10&#34;)。当我在给定的ImageView上使用百分比时,怎么可能呢?

1 个答案:

答案 0 :(得分:0)

看起来这是一个愚蠢的初学者错误,我不想看到或想要忽略它;)

width / 100不是float值,而是int值。然后整个计算由于错误的值而失败,而这个假值就是多重的。

我更改了我的代码,现在这是一个工作代码段