1

I am trying to get the dimensions of my RelativeLayout.

I am told by many to use the following codes:

    RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.myRelativeLayout);
    int layoutWidth = relativeLayout.getWidth();
    int layoutHeight = relativeLayout.getHeight();

My problem is that all the ids I can find in my R.id are all buttons, text views, and all that kind. There is nothing like layout id at all!

Then I try to write:

relativeLayout = (RelativeLayout) findViewById(R.layout.main_activity); 

relativeLayout is null when run. So it is also incorrect.

Do I need to add the layout id manually into R.id? I don't think so.

But why there is no id for the layout in R.id?

4

1 回答 1

3

这取决于你的意思是什么布局。默认情况下,当您创建活动或 XML 布局时,它将存储为 R.layout.xxx 。但是可以说,在一个布局中,你有另一个布局(在这种情况下是嵌套布局),你必须手动“id”你想要引用的布局。

例如:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <RelativeLayout
        android:id="@+id/CallMe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="139dp"
        android:layout_marginTop="130dp" >
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="@+layout/test"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/CallMe"
        android:layout_below="@+id/CallMe"
        android:layout_marginTop="64dp" >
    </RelativeLayout>

</RelativeLayout>

然后,您可以通过 R.id.CallMe 参考第一个相对布局,通过 R.layout.test 参考第二个相对布局

您可以将其命名为任何名称,它不必是 la​​yout 或 id。希望有帮助

于 2013-07-15T03:23:43.550 回答