No RelativeLayout id in R.id while Getting dimensions of RelativeLayout

╄→гoц情女王★ 提交于 2019-12-11 09:42:50

问题


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?


回答1:


That depends on what layout do you mean. By default, when you create an activity or a XML layout, it will be stored as R.layout.xxx . But lets say, inside a layout, you have another layout (nested layout in this case), you have to manually "id" the layout that you want to refer to.

For example:

<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>

You can then refer to the first relative layout by R.id.CallMe and the second one by R.layout.test

You can name it anything, it doesn't has to be layout or id. Hope that helps



来源:https://stackoverflow.com/questions/17646188/no-relativelayout-id-in-r-id-while-getting-dimensions-of-relativelayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!