Android layout 与ImageView的RelativeLayout-计算元素的位置
我的android代码有问题。我有以下代码Android layout 与ImageView的RelativeLayout-计算元素的位置,android-layout,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="matc
<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>
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”)上的位置是正确的,但在平板电脑(10)等其他设备上则不正确。当我在给定的ImageView上使用百分比时,这怎么可能呢?看起来这是一个愚蠢的初学者错误,我不想看到或想忽略它;) width/100返回的不是浮点值,而是int值。然后由于一个被乘的假值,整个计算失败 我改变了我的代码,现在它是一个工作片段